chain-insights 0.19.0 → 0.22.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 (138) hide show
  1. package/README.md +44 -121
  2. package/bin/cli.js +4 -4
  3. package/bin/install.cjs +137 -113
  4. package/bin/mcp-proxy.cjs +7 -5
  5. package/dist/{action-log-Dfe88TwV.cjs → action-log-HniMMF7f.cjs} +1 -1
  6. package/dist/action-log-diTHyMbV.mjs.map +1 -1
  7. package/dist/active-BQopLul8.mjs.map +1 -1
  8. package/dist/{active-Bj6dohpc.cjs → active-Bc13hJIm.cjs} +1 -1
  9. package/dist/{app-CJwx_2Rr.mjs → app-7NRCqx_Q.mjs} +2 -2
  10. package/dist/app-7NRCqx_Q.mjs.map +1 -0
  11. package/dist/{app-D4Cm69ob.cjs → app-l9JE6bt3.cjs} +5 -5
  12. package/dist/{artifact-server-sJBFGcum.cjs → artifact-server-CH-asxF5.cjs} +3 -2
  13. package/dist/{artifact-server-D1D-_t5l.mjs → artifact-server-DoxJr0z8.mjs} +4 -3
  14. package/dist/artifact-server-DoxJr0z8.mjs.map +1 -0
  15. package/dist/{capabilities-CxvK7LKZ.mjs → capabilities-BZI6qROg.mjs} +2 -2
  16. package/dist/capabilities-BZI6qROg.mjs.map +1 -0
  17. package/dist/{capabilities-CZYijWbg.cjs → capabilities-CPcrxodx.cjs} +2 -2
  18. package/dist/cli.cjs +42 -216
  19. package/dist/cli.mjs +36 -210
  20. package/dist/cli.mjs.map +1 -1
  21. package/dist/{client-Bjxo7AEa.cjs → client-CqAzD519.cjs} +4 -4
  22. package/dist/{client-i3WtsKA4.mjs → client-D4aM4bzP.mjs} +4 -4
  23. package/dist/client-D4aM4bzP.mjs.map +1 -0
  24. package/dist/{config-DE0dUT3P.cjs → config-BVFf3v8-.cjs} +2 -2
  25. package/dist/{config-DA6KRx60.mjs → config-CnNMdt4M.mjs} +2 -2
  26. package/dist/config-CnNMdt4M.mjs.map +1 -0
  27. package/dist/graph-normalizer-BA3Rbd6l.mjs.map +1 -1
  28. package/dist/graph-reports-B6yoYbPq.mjs.map +1 -1
  29. package/dist/{graph-reports-DSHSp5HL.cjs → graph-reports-_gqzxvvs.cjs} +2 -2
  30. package/dist/{html-generator-Ui29DLSD.cjs → html-generator-B9f_GIi2.cjs} +4 -3
  31. package/dist/{html-generator-ClysZjfY.mjs → html-generator-D2BDzLED.mjs} +3 -2
  32. package/dist/{html-generator-ClysZjfY.mjs.map → html-generator-D2BDzLED.mjs.map} +1 -1
  33. package/dist/index.cjs +9 -9
  34. package/dist/index.d.cts +3 -0
  35. package/dist/index.d.cts.map +1 -1
  36. package/dist/index.d.mts +3 -0
  37. package/dist/index.d.mts.map +1 -1
  38. package/dist/index.mjs +9 -9
  39. package/dist/{init-BT3STWBv.mjs → init-Djhml4ih.mjs} +3 -3
  40. package/dist/init-Djhml4ih.mjs.map +1 -0
  41. package/dist/{init-BR4SRTAY.cjs → init-DvrKxK15.cjs} +3 -3
  42. package/dist/limits-D3Mn-gig.mjs.map +1 -1
  43. package/dist/mcp-endpoint-DbWtLcba.mjs.map +1 -1
  44. package/dist/mcp-proxy.cjs +19 -18
  45. package/dist/mcp-proxy.d.cts.map +1 -1
  46. package/dist/mcp-proxy.d.mts.map +1 -1
  47. package/dist/mcp-proxy.mjs +13 -12
  48. package/dist/mcp-proxy.mjs.map +1 -1
  49. package/dist/{merge-CJRZpuZ4.mjs → merge-BZw-pMPN.mjs} +2 -2
  50. package/dist/merge-BZw-pMPN.mjs.map +1 -0
  51. package/dist/{merge-B_5kxbGv.cjs → merge-C52eaAGU.cjs} +1 -1
  52. package/dist/{output-root-C1PFNCqb.cjs → output-root-BewoQaTx.cjs} +2 -2
  53. package/dist/{public-tools-CgiKgYgf.cjs → public-tools-BFs_7U_Z.cjs} +8 -7
  54. package/dist/{public-tools-B9_wXs2o.mjs → public-tools-BjqZGGAC.mjs} +7 -6
  55. package/dist/public-tools-BjqZGGAC.mjs.map +1 -0
  56. package/dist/{rolldown-runtime-DakpK96I.cjs → rolldown-runtime-C0BPl7ul.cjs} +1 -1
  57. package/dist/{schema-DF0aOXII.cjs → schema-BpeV3xDV.cjs} +5 -2
  58. package/dist/{schema-0BVyF-aL.mjs → schema-DOJA2nNi.mjs} +5 -2
  59. package/dist/schema-DOJA2nNi.mjs.map +1 -0
  60. package/dist/{schema-cache-DwDvPy4e.mjs → schema-cache-DJdU4MIP.mjs} +2 -2
  61. package/dist/{schema-cache-DwDvPy4e.mjs.map → schema-cache-DJdU4MIP.mjs.map} +1 -1
  62. package/dist/{schema-cache-CX0r2UQp.cjs → schema-cache-n7Gbhvsj.cjs} +2 -2
  63. package/dist/{server-ta1oyJ2a.cjs → server-CmvzYu7v.cjs} +4 -3
  64. package/dist/{server-BXj6BRI1.mjs → server-mDSRgk1X.mjs} +4 -3
  65. package/dist/server-mDSRgk1X.mjs.map +1 -0
  66. package/dist/tool-visibility-C0ALejXI.mjs.map +1 -1
  67. package/dist/{tool-visibility-DMIEexib.cjs → tool-visibility-DZBAP62b.cjs} +1 -1
  68. package/dist/{tools-CWwX4yth.mjs → tools-BKLnlBG1.mjs} +8 -6
  69. package/dist/tools-BKLnlBG1.mjs.map +1 -0
  70. package/dist/{tools-BPfUpCUR.cjs → tools-lPY6k-vJ.cjs} +8 -6
  71. package/dist/{topup-server-VGl8-Fz5.cjs → topup-server-DAqmAuu1.cjs} +23 -21
  72. package/dist/{topup-server-D2X7My7i.mjs → topup-server-rqI7bqem.mjs} +23 -21
  73. package/dist/topup-server-rqI7bqem.mjs.map +1 -0
  74. package/dist/update-CJUfGCxs.mjs.map +1 -1
  75. package/dist/{usage-status-H1xgCu99.cjs → usage-status-BdwwgYsu.cjs} +2 -2
  76. package/dist/{usage-status-D2uosC7s.mjs → usage-status-CHiOPA-2.mjs} +2 -2
  77. package/dist/usage-status-CHiOPA-2.mjs.map +1 -0
  78. package/dist/version-BA3J8hu4.mjs.map +1 -1
  79. package/dist/{viz-HSwLcKr6.cjs → viz-BJ_kyRjI.cjs} +7 -5
  80. package/dist/{viz-Cq1jSWSH.mjs → viz-Uh_EF-qB.mjs} +6 -4
  81. package/dist/viz-Uh_EF-qB.mjs.map +1 -0
  82. package/dist/{wallet-C2yVjcSY.cjs → wallet-BEvHrHi3.cjs} +3 -2
  83. package/dist/{wallet-BrTTnf7w.mjs → wallet-fMbhvKXT.mjs} +3 -2
  84. package/dist/wallet-fMbhvKXT.mjs.map +1 -0
  85. package/docs/architecture.md +18 -18
  86. package/docs/debugging.md +2 -42
  87. package/docs/development.md +0 -27
  88. package/docs/graph-query-compatibility.md +66 -57
  89. package/docs/graph-tools.md +6 -6
  90. package/docs/investigation-workspaces.md +0 -35
  91. package/docs/mcp-proxy.md +8 -9
  92. package/docs/search-limits.md +8 -8
  93. package/docs/stability.md +4 -5
  94. package/package.json +1 -5
  95. package/skills/chain-insights-cypher/SKILL.md +7 -7
  96. package/skills/chain-insights-cypher/agents/openai.yaml +3 -3
  97. package/skills/chain-insights-schema-bittensor/SKILL.md +26 -26
  98. package/skills/chain-insights-schema-evm/SKILL.md +37 -37
  99. package/dist/app-CJwx_2Rr.mjs.map +0 -1
  100. package/dist/artifact-server-D1D-_t5l.mjs.map +0 -1
  101. package/dist/capabilities-CxvK7LKZ.mjs.map +0 -1
  102. package/dist/cases-C1XewLdx.mjs +0 -155
  103. package/dist/cases-C1XewLdx.mjs.map +0 -1
  104. package/dist/cases-CVtc7Rf8.cjs +0 -160
  105. package/dist/client-i3WtsKA4.mjs.map +0 -1
  106. package/dist/config-CwIb-tav.mjs +0 -33
  107. package/dist/config-CwIb-tav.mjs.map +0 -1
  108. package/dist/config-Cy-qzx4W.cjs +0 -33
  109. package/dist/config-DA6KRx60.mjs.map +0 -1
  110. package/dist/init-9jY5rCcH.cjs +0 -24
  111. package/dist/init-BT3STWBv.mjs.map +0 -1
  112. package/dist/init-BiRfMQcA.mjs +0 -26
  113. package/dist/init-BiRfMQcA.mjs.map +0 -1
  114. package/dist/lock-Cs-a3Ng1.cjs +0 -38
  115. package/dist/lock-D_sWGS7W.mjs +0 -40
  116. package/dist/lock-D_sWGS7W.mjs.map +0 -1
  117. package/dist/merge-CJRZpuZ4.mjs.map +0 -1
  118. package/dist/paths-CffVTUCv.cjs +0 -31
  119. package/dist/paths-_3isihzD.mjs +0 -21
  120. package/dist/paths-_3isihzD.mjs.map +0 -1
  121. package/dist/public-tools-B9_wXs2o.mjs.map +0 -1
  122. package/dist/render-TmSq0f4f.cjs +0 -207
  123. package/dist/render-mxE0Tdsf.mjs +0 -206
  124. package/dist/render-mxE0Tdsf.mjs.map +0 -1
  125. package/dist/report-BFXFrJmj.mjs +0 -36
  126. package/dist/report-BFXFrJmj.mjs.map +0 -1
  127. package/dist/report-BwKQqOCR.cjs +0 -36
  128. package/dist/runner-CSss8Hvy.mjs +0 -33
  129. package/dist/runner-CSss8Hvy.mjs.map +0 -1
  130. package/dist/runner-aErdz2zn.cjs +0 -31
  131. package/dist/schema-0BVyF-aL.mjs.map +0 -1
  132. package/dist/server-BXj6BRI1.mjs.map +0 -1
  133. package/dist/tools-CWwX4yth.mjs.map +0 -1
  134. package/dist/topup-server-D2X7My7i.mjs.map +0 -1
  135. package/dist/usage-status-D2uosC7s.mjs.map +0 -1
  136. package/dist/viz-Cq1jSWSH.mjs.map +0 -1
  137. package/dist/wallet-BrTTnf7w.mjs.map +0 -1
  138. package/docs/monitoring.md +0 -277
@@ -1 +1 @@
1
- {"version":3,"file":"mcp-proxy.mjs","names":[],"sources":["../src/mcp/proxy.ts"],"sourcesContent":["import { readFileSync } from 'node:fs'\nimport { appendFile, mkdir } from 'node:fs/promises'\nimport path from 'node:path'\nimport { fileURLToPath } from 'node:url'\nimport { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'\nimport { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'\nimport { Client } from '@modelcontextprotocol/sdk/client/index.js'\nimport { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js'\nimport type { ContentBlock, GetPromptResult } from '@modelcontextprotocol/sdk/types.js'\nimport { registerAppResource, registerAppTool, RESOURCE_MIME_TYPE } from '@modelcontextprotocol/ext-apps/server'\nimport * as z from 'zod'\nimport type { InvestigatorConfig } from '../config/schema.js'\nimport { PACKAGE_VERSION } from '../version.js'\nimport type { McpTool } from './schema-cache.js'\nimport { HIDDEN_REMOTE_TOOL_NAMES, PUBLIC_MCP_TOOL_ALLOWED_ARGS, PUBLIC_MCP_TOOL_REQUIRED_ARGS } from './tool-visibility.js'\nimport { PaymentRequiredError } from './client.js'\nimport { primitiveBackendUsageStatus } from './usage-status.js'\nimport { mirrorGraphNetworkCapabilities } from './capabilities.js'\nimport { actionLogSignalsFromResult, appendActionLog } from './action-log.js'\n\nconst LOCAL_TOOL_NAMES = new Set([\n 'meta_network_capabilities',\n 'meta_usage_status',\n 'meta_help',\n 'wallet_balance',\n])\nconst GRAPH_RESOURCE_URI = 'ui://chain-insights/graph'\nconst GRAPH_APP_TOOL_NAMES = new Set([\n 'aml_address_risk',\n])\nconst GRAPH_ARRAY_KEYS = ['nodes', 'edges', 'flows', 'edge_anchors'] as const\nconst __dirname = path.dirname(fileURLToPath(import.meta.url))\n\nexport type McpProxyMode = 'workspace' | 'stateless'\n\nexport function resolveMcpProxyMode(env: NodeJS.ProcessEnv = process.env): McpProxyMode {\n const raw = env['CHAIN_INSIGHTS_MCP_PROXY_MODE']?.trim().toLowerCase()\n if (!raw || raw === 'workspace') return 'workspace'\n if (raw === 'stateless' || raw === 'no-workspace' || raw === 'workspace-less') return 'stateless'\n throw new Error(`CHAIN_INSIGHTS_MCP_PROXY_MODE must be workspace or stateless; got \"${raw}\"`)\n}\n\nconst KNOWN_PUBLIC_TOOL_DESCRIPTIONS: Record<string, string> = {\n meta_network_capabilities: 'Return the current Chain Insights network and tool support matrix.',\n meta_usage_status: \"Return the caller's public free graph_query quota for the current UTC day.\",\n meta_help: 'Show a short guide to Chain Insights tools and workflow.',\n wallet_balance: 'Show the local Chain Insights payment wallet address, payment network, token, and amount.',\n aml_address_risk: 'Screen one blockchain address for AML risk, behavior patterns, neighborhood context, exchange exposure, and optional comparison with another address. Topology reads cover full lifetime history in one unified graph.',\n graph_query: 'Run a read-only GQL/Cypher query through the Chain Insights graph endpoint. Use USE topology for topology (address/FLOWS_TO/LINKED graph, unified recent+historical, plus the node risk_score/risk_level verdict) and USE facts for bounded TRANSFER rows and enrichment. Preserve full addresses exactly.',\n graph_query_batch: 'Run multiple read-only GQL/Cypher queries through the Chain Insights graph endpoint in one paid batch. Prefer this for related topology/facts reads.',\n}\nconst FALLBACK_GRAPH_PRIMITIVE_TOOL_NAMES = ['graph_query', 'graph_query_batch'] as const\n\ntype ToolInputShape = Record<string, z.ZodTypeAny>\ntype ToolHandler = (args: unknown, extra?: unknown) => Promise<unknown> | unknown\ntype ToolRegistrationConfig = Parameters<McpServer['registerTool']>[1]\ntype ToolCallInput = { name: string; arguments?: Record<string, unknown> }\ntype RemoteToolCaller = {\n callTool: Client['callTool']\n}\ntype ChainInsightsGraphMeta = {\n schema: string\n url: string\n}\n\nconst NETWORK_DESCRIPTION = 'Network to query. Call meta_network_capabilities first and pass a name GraphRAG advertised. CIA does not pick a default network.'\nconst NETWORK_SCHEMA = z.string().min(1).describe(NETWORK_DESCRIPTION)\n\nconst EMPTY_INPUT_SCHEMA = z.strictObject({})\nconst REMOTE_GRAPH_TOOL_REQUEST_TIMEOUT_MS = 15 * 60 * 1000\n\nconst CHAIN_INSIGHTS_WORKFLOW = [\n 'Workflow:',\n '1. Chain Insights workspaces are append-only local working directories. Bootstrap with cia init before workflows that persist artifacts.',\n '2. Do not call investigation tools until required arguments are known. Network is required; use meta_network_capabilities to check supported networks and available tools, or ask the user if missing.',\n '3. Use aml_address_risk for single-address enrichment. Use graph_query(_batch) for graph-level questions that aml_address_risk does not answer.',\n '4. Persisted outputs belong in the initialized workspace under reports/, reports/graphs/, reports/tables/, artifacts/, entities/, sessions/, and published/.',\n '5. For local review, inspect the generated Markdown and graph/table artifacts directly in the workspace.',\n].join('\\n')\n\nconst GRAPH_SCHEMA_HINTS = [\n 'Graph query hints:',\n '- Call meta_network_capabilities first. Pass network= exactly as GraphRAG advertised it. CIA does not pick a default network.',\n '- The graph is address-grain. The only topology money node label is Address, keyed by the raw chain-native H160 address on EVM networks, for example 0x1874a43d7c6d888f9eda3d22a3a49704e3cadb24. The network value on Address nodes matches the tool argument. There is no separate identity key.',\n '- Address nodes carry address, network, labels, and is_exchange. (:Address)-[:LINKED]-(:Address) is an undirected ownership-overlay edge (basis derived/associated, plus confidence, source_event, declared_owner) asserting the two addresses are controlled by the same actor. LINKED is served on the topology graph only. Enumerate LINKED neighbors with MATCH (a:Address {address: $addr})-[l:LINKED]-(b:Address) RETURN b.address, b.network, l.basis, l.confidence.',\n '- Address nodes also carry a risk verdict (risk_score float, risk_level string) plus base activity rollups: degree_in/degree_out/degree_total (distinct counterparty addresses), tx_in_count/tx_out_count/tx_total_count, total_in_usd/total_out_usd/total_volume_usd, net_flow_usd (in minus out; positive = net receiver) — all computed from external flows only — and first_activity_timestamp/last_activity_timestamp/activity_span_days, which include all flows (self-loops included). FLOWS_TO edges carry tx_count, amount_usd_sum, avg_tx_size_usd (understates when price_coverage_ratio < 1), first/last_seen_timestamp, first/last_tx_id, price_coverage_ratio. Lifetime aggregates are the only serving window.',\n '- For actor-level exposure (AC11), UNION FLOWS_TO reachability over one visible LINKED hop instead of expanding through the LINKED edge itself: MATCH (a:Address {address: $addr})-[:LINKED]-(owned:Address)-[r:FLOWS_TO]-(b:Address) WHERE owned.address <> b.address AND a.address <> b.address RETURN owned.address, b.address, r.amount_usd_sum.',\n '- The risk verdict lives on topology nodes (risk_score float, risk_level string). Labels and per-label risk also live on the address node (labels array + label_risk entries: label, risk_level, updated_timestamp). USE facts serves bounded individual transfer rows (TRANSFER edges) only; lifetime address metrics (degrees, totals, activity window) are node properties on USE topology.',\n '- (from:Address)-[t:TRANSFER]->(to:Address) on USE facts returns individual transfer rows, not aggregates, with properties amount, amount_usd, asset_symbol, asset_contract, tx_id, block_height, block_timestamp, event_index, edge_index, price_usd, and price_missing. Every TRANSFER query — row-select or count()/sum() aggregate — requires an indexed predicate: address equality on either endpoint (for example {address: \"...\"} on from or to) or a WHERE t.tx_id = \"...\" equality; a bare LIMIT with no indexed predicate is rejected, since facts_transfers_view is a full transfer-history table, not a small per-address dimension view.',\n '- Facts graph labels include Address; the TRANSFER relationship connects two Address nodes. Facts address keys match topology address values exactly.',\n '- Topology relationships include FLOWS_TO, LINKED, and RISK_PROXIMITY between Address nodes.',\n '- FLOWS_TO properties commonly carry tx_count, amount_usd_sum, avg_tx_size_usd, first_seen_timestamp, last_seen_timestamp, first_tx_id, last_tx_id, price_coverage_ratio. Confirm available fields through runtime schema before relying on them.',\n '- Traversal rule: for BFS, fixed-hop fallback, shortest-path, or manual FLOWS_TO traversal, exchange hot wallets are terminal endpoints only. Do not expand from, through, or classify exchange nodes as deposit, suspect, or intermediate candidates; filter every non-terminal node with is_exchange IS NULL.',\n '- Start schema discovery with endpoint-safe property reads: MATCH (n:Address) WHERE n.address IS NOT NULL RETURN n.address AS address, n.network AS network, n.labels AS labels, n.risk_score AS risk_score, n.risk_level AS risk_level LIMIT 20',\n '- Relationship discovery: MATCH (:Address)-[r:FLOWS_TO]->(:Address) RETURN r.amount_usd_sum AS amount_usd_sum, r.tx_count AS tx_count LIMIT 20',\n '- graph_query uses the active Chain Insights graph endpoint. Select the graph with USE topology for topology (address/FLOWS_TO/LINKED graph, unified recent+historical, plus the node risk_score/risk_level verdict) and USE facts for bounded TRANSFER rows and enrichment; address is the node grain, not the topology name.',\n '- All graph_query calls are read-only. Never use CREATE, INSERT, MERGE, SET, DELETE, REMOVE, DROP, DETACH, ADD, CONNECT, DISCONNECT, ALTER, TRUNCATE, GRANT, or REVOKE.',\n '- Use USE facts graph patterns for fact and enrichment reads. Do not query internal table namespaces directly.',\n].join('\\n')\n\nconst GRAPH_REPORT_HINTS = [\n 'Graph visualization behavior:',\n '- Graph-backed tools return the investigator report as text content and keep raw graph data out of LLM-visible structuredContent.',\n '- Chain Insights prepares the graph view automatically from local workspace report files when graph metadata is available.',\n '- If the graph view cannot load a report, retry the graph-backed tool call so Chain Insights can recreate the local graph report.',\n].join('\\n')\n\nconst SERVER_INSTRUCTIONS = [\n 'Chain Insights is a local graph-analysis workspace for AI agents.',\n CHAIN_INSIGHTS_WORKFLOW,\n GRAPH_REPORT_HINTS,\n GRAPH_SCHEMA_HINTS,\n 'Presentation rules: preserve tool summaries as returned; never truncate blockchain addresses or identity_resolution audit mappings.',\n].join('\\n\\n')\n\nconst STATELESS_SERVER_INSTRUCTIONS = [\n 'Chain Insights is running as a stateless AML proxy for a host application.',\n 'Do not use local workspace persistence, wallet, or graph report workflows in this mode.',\n 'Use meta_network_capabilities first when network support is unknown, then call aml_address_risk, graph_query, or graph_query_batch as needed.',\n GRAPH_SCHEMA_HINTS,\n 'Presentation rules: preserve tool summaries as returned; never truncate blockchain addresses or identity_resolution audit mappings.',\n].join('\\n\\n')\n\nfunction readGraphAppHtml(): string {\n const candidates = [\n path.resolve(__dirname, 'templates', 'graph.html'),\n path.resolve(__dirname, '..', 'templates', 'graph.html'),\n path.resolve(__dirname, '..', 'viz', 'templates', 'graph.html'),\n ]\n\n for (const candidate of candidates) {\n try {\n return readFileSync(candidate, 'utf8')\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code !== 'ENOENT') throw err\n }\n }\n\n throw new Error(`Chain Insights Graph app template not found. Tried: ${candidates.join(', ')}`)\n}\n\nfunction graphArtifactOrigins(config: Pick<InvestigatorConfig, 'serverPort'>): string[] {\n return [\n `http://127.0.0.1:${config.serverPort}`,\n `http://localhost:${config.serverPort}`,\n ]\n}\n\nfunction hasGraphApp(tool: McpTool): boolean {\n const configuredUri = tool._meta?.ui\n if (\n configuredUri &&\n typeof configuredUri === 'object' &&\n 'resourceUri' in configuredUri &&\n configuredUri.resourceUri === GRAPH_RESOURCE_URI\n ) {\n return true\n }\n\n if (tool._meta?.['ui/resourceUri'] === GRAPH_RESOURCE_URI) return true\n if (GRAPH_APP_TOOL_NAMES.has(tool.name)) return true\n return JSON.stringify(tool.outputSchema ?? {}).includes('\"app_data\"')\n}\n\nfunction graphToolMeta(tool: McpTool): Record<string, unknown> & { ui: { resourceUri: string } } {\n const meta = { ...(tool._meta ?? {}) }\n const ui =\n meta.ui && typeof meta.ui === 'object' && !Array.isArray(meta.ui)\n ? { ...(meta.ui as Record<string, unknown>) }\n : {}\n\n return {\n ...meta,\n ui: {\n ...ui,\n resourceUri: GRAPH_RESOURCE_URI,\n },\n }\n}\n\n// Exported so a test can prove, for EVERY public tool, that each declared\n// schema argument also appears in PUBLIC_MCP_TOOL_ALLOWED_ARGS. An argument\n// present here but missing there is silently stripped by\n// normalizeRemoteToolArguments and the caller never learns their override was\n// ignored — the failure mode that shipped with `time_scope`.\nexport function knownPublicToolInputSchema(toolName: string): ToolInputShape | null {\n switch (toolName) {\n case 'aml_address_risk':\n return {\n address: z.string().min(1).describe('Blockchain address to screen.'),\n network: NETWORK_SCHEMA,\n compare_address: z.string().optional().describe('Optional address to compare against the screened address.'),\n include_attachments: z.boolean().optional().describe('Include graph app report metadata'),\n }\n case 'graph_query':\n return {\n query: z.string().min(1).describe('Read-only GQL/Cypher query. Use USE topology for topology (address/FLOWS_TO/LINKED graph, unified recent+historical, plus the node risk_score/risk_level verdict) and USE facts for bounded TRANSFER rows and enrichment.'),\n network: NETWORK_SCHEMA,\n }\n case 'graph_query_batch':\n return {\n network: NETWORK_SCHEMA,\n queries: z.array(z.object({\n id: z.string().optional(),\n query: z.string().min(1).describe('Read-only GQL/Cypher query'),\n })).min(1).max(20),\n per_query_timeout_seconds: z.number().int().min(1).max(600).optional(),\n }\n default:\n return null\n }\n}\n\nfunction fallbackGraphPrimitiveTools(): McpTool[] {\n return FALLBACK_GRAPH_PRIMITIVE_TOOL_NAMES.map((name) => ({\n name,\n description: KNOWN_PUBLIC_TOOL_DESCRIPTIONS[name],\n }))\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return !!value && typeof value === 'object' && !Array.isArray(value)\n}\n\nfunction redactLogValue(value: unknown): unknown {\n if (Array.isArray(value)) return value.map(redactLogValue)\n if (!isRecord(value)) return value\n return Object.fromEntries(Object.entries(value).map(([key, entry]) => {\n if (/token|secret|password|private.?key|authorization/i.test(key)) return [key, '[redacted]']\n return [key, redactLogValue(entry)]\n }))\n}\n\nfunction errorForLog(err: unknown): Record<string, unknown> {\n const error = err as Error\n return {\n name: error.name ?? 'Error',\n message: error.message ?? String(err),\n }\n}\n\nfunction sanitizeCypher(query: string): string {\n return query.replace(/\\s+/g, ' ').trim()\n}\n\nfunction cypherLogPayload(tool: string, args: unknown): Record<string, unknown> | null {\n if (!isRecord(args)) return null\n if (tool === 'graph_query') {\n return {\n network: args.network,\n queries: [{\n id: tool,\n query: typeof args.query === 'string' ? sanitizeCypher(args.query) : args.query,\n }],\n }\n }\n if (tool === 'graph_query_batch') {\n const queries = Array.isArray(args.queries) ? args.queries : []\n return {\n network: args.network,\n per_query_timeout_seconds: args.per_query_timeout_seconds,\n query_count: queries.length,\n queries: queries.map((entry, index) => isRecord(entry)\n ? {\n id: typeof entry.id === 'string' ? entry.id : `q${index + 1}`,\n query: typeof entry.query === 'string' ? sanitizeCypher(entry.query) : entry.query,\n }\n : { id: `q${index + 1}`, query: entry }),\n }\n }\n return null\n}\n\nfunction createMcpLogger(config: Pick<InvestigatorConfig, 'dataDir'>) {\n const disabled = process.env.CHAIN_INSIGHTS_MCP_LOG === '0'\n const filePath = process.env.CHAIN_INSIGHTS_MCP_LOG_PATH?.trim() || path.join(config.dataDir, '.chain-insights', 'runtime', 'logs', 'mcp-proxy.jsonl')\n\n async function write(level: 'info' | 'error', event: string, fields: Record<string, unknown> = {}): Promise<void> {\n if (disabled) return\n try {\n await mkdir(path.dirname(filePath), { recursive: true })\n await appendFile(filePath, JSON.stringify({\n ts: new Date().toISOString(),\n level,\n event,\n pid: process.pid,\n ...fields,\n }) + '\\n', { mode: 0o600 })\n } catch {\n // Logging must never break the stdio MCP server.\n }\n }\n\n return {\n filePath,\n info: (event: string, fields?: Record<string, unknown>) => write('info', event, fields),\n error: (event: string, fields?: Record<string, unknown>) => write('error', event, fields),\n }\n}\n\nfunction installToolLogging(server: McpServer, logger: ReturnType<typeof createMcpLogger>): void {\n const existingRegisterTool = server.registerTool\n const originalRegisterTool = existingRegisterTool.bind(server)\n const wrappedRegisterTool = ((name: string, config: ToolRegistrationConfig, handler: ToolHandler) => {\n const wrapped: ToolHandler = async (args, extra) => {\n const startedAt = Date.now()\n await logger.info('tool.start', {\n tool: name,\n args: redactLogValue(args),\n })\n try {\n const result = await handler(args, extra)\n const isError = isRecord(result) && result.isError === true\n await logger.info('tool.end', {\n tool: name,\n duration_ms: Date.now() - startedAt,\n is_error: isError,\n })\n return result\n } catch (err) {\n await logger.error('tool.throw', {\n tool: name,\n duration_ms: Date.now() - startedAt,\n error: errorForLog(err),\n })\n throw err\n }\n }\n return originalRegisterTool(name, config, wrapped as never)\n }) as typeof server.registerTool\n Object.assign(wrappedRegisterTool, existingRegisterTool)\n server.registerTool = wrappedRegisterTool\n}\n\nfunction installRemoteCypherLogging(remoteClient: RemoteToolCaller, logger: ReturnType<typeof createMcpLogger>): void {\n const existingCallTool = remoteClient.callTool\n const originalCallTool = existingCallTool.bind(remoteClient)\n const wrappedCallTool = (async (...args: Parameters<Client['callTool']>) => {\n const input = args[0] as ToolCallInput\n const queryPayload = cypherLogPayload(input.name, input.arguments)\n const toolArgs = input.arguments ?? {}\n const startedAt = Date.now()\n if (queryPayload) {\n await logger.info('topology.start', {\n tool: input.name,\n ...queryPayload,\n })\n }\n try {\n const result = await originalCallTool(...args)\n if (queryPayload) {\n await logger.info('topology.end', {\n tool: input.name,\n duration_ms: Date.now() - startedAt,\n is_error: isRecord(result) && result.isError === true,\n })\n }\n const { warnings, search_limits } = actionLogSignalsFromResult(result)\n await appendActionLog({\n timestamp: startedAt,\n tool: input.name,\n args: toolArgs,\n outcome: 'ok',\n duration_ms: Date.now() - startedAt,\n warnings,\n search_limits,\n })\n return result\n } catch (err) {\n if (queryPayload) {\n await logger.error('cypher.throw', {\n tool: input.name,\n duration_ms: Date.now() - startedAt,\n error: errorForLog(err),\n })\n }\n await appendActionLog({\n timestamp: startedAt,\n tool: input.name,\n args: toolArgs,\n outcome: 'error',\n duration_ms: Date.now() - startedAt,\n error: (err as Error).message,\n })\n throw err\n }\n }) as typeof remoteClient.callTool\n Object.assign(wrappedCallTool, existingCallTool)\n remoteClient.callTool = wrappedCallTool\n}\n\nfunction remoteToolRequestOptions(toolName: string): Parameters<Client['callTool']>[2] | undefined {\n if (toolName === 'graph_query' || toolName === 'graph_query_batch') {\n return {\n timeout: REMOTE_GRAPH_TOOL_REQUEST_TIMEOUT_MS,\n maxTotalTimeout: REMOTE_GRAPH_TOOL_REQUEST_TIMEOUT_MS,\n }\n }\n return undefined\n}\n\nfunction isBlankArgument(value: unknown): boolean {\n if (value === undefined || value === null) return true\n if (typeof value === 'string') return value.trim() === ''\n if (Array.isArray(value)) return value.length === 0 || value.every(isBlankArgument)\n return false\n}\n\nfunction normalizeRemoteToolArguments(toolName: string, args: unknown): Record<string, unknown> {\n const normalized = isRecord(args) ? { ...args } : {}\n if (!(toolName in PUBLIC_MCP_TOOL_REQUIRED_ARGS)) return normalized\n\n const allowedArgs = PUBLIC_MCP_TOOL_ALLOWED_ARGS[toolName]\n if (!allowedArgs) return normalized\n return Object.fromEntries(Object.entries(normalized).filter(([key]) => allowedArgs.includes(key)))\n}\n\nfunction validateKnownPublicToolArguments(\n toolName: string,\n args: Record<string, unknown>,\n): string | null {\n const requiredArgs = PUBLIC_MCP_TOOL_REQUIRED_ARGS[toolName]\n if (!requiredArgs) return null\n\n for (const argName of requiredArgs) {\n if (isBlankArgument(args[argName])) {\n return `Missing required argument: ${argName}`\n }\n }\n\n return null\n}\n\nfunction claudeFacingToolDescription(tool: McpTool): string {\n const baseDescription = KNOWN_PUBLIC_TOOL_DESCRIPTIONS[tool.name] ?? tool.description ?? tool.name\n const requiredArgs = PUBLIC_MCP_TOOL_REQUIRED_ARGS[tool.name]\n if (!requiredArgs) return baseDescription\n return [\n baseDescription,\n '',\n `Required arguments: ${requiredArgs.join(', ')}.`,\n 'If the user did not provide the network, ask for it before calling this tool. Do not guess a default network.',\n ].join('\\n')\n}\n\nfunction knownPublicToolAnnotations(toolName: string): Record<string, boolean> | undefined {\n if (\n toolName === 'graph_query' ||\n toolName === 'graph_query_batch' ||\n toolName.startsWith('aml_')\n ) {\n return {\n readOnlyHint: true,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: true,\n }\n }\n return undefined\n}\n\ntype RemoteToolResult = {\n content?: ContentBlock[]\n structuredContent?: Record<string, unknown>\n _meta?: Record<string, unknown>\n isError?: boolean\n}\n\nfunction promptResult(text: string, description?: string): GetPromptResult {\n return {\n description,\n messages: [\n {\n role: 'user',\n content: {\n type: 'text',\n text,\n },\n },\n ],\n }\n}\n\nfunction registerLocalPrompts(server: McpServer): void {\n server.registerPrompt(\n 'aml-address-risk',\n {\n title: 'AML Address Risk',\n description: 'Screen a blockchain address for AML risk, behavioral patterns, neighborhood profile, member addresses, and exchange links.',\n argsSchema: {\n network: NETWORK_SCHEMA,\n address: z.string().describe('Blockchain address to screen'),\n compare_address: z.string().optional().describe('Optional address to compare against the screened address'),\n },\n },\n async ({ network, address, compare_address }) => promptResult(\n [\n `Use Chain Insights aml_address_risk on ${network} for:`,\n '',\n `\\`${address}\\``,\n compare_address ? `\\nCompare with: \\`${compare_address}\\`` : '',\n '',\n 'Present the summary as-is. Do not add analysis, verdicts, or risk assessments; the tool output already contains the risk assessment.',\n ].filter(Boolean).join('\\n'),\n 'AML address risk screening',\n ),\n )\n\n server.registerPrompt(\n 'meta-network-capabilities',\n {\n title: 'Network Capabilities',\n description: 'Inspect supported networks and available tools before selecting a network.',\n argsSchema: {},\n },\n async () => promptResult(\n 'Use Chain Insights meta_network_capabilities. Report only the supported networks and available tools exactly as returned; do not infer unsupported networks.',\n 'Network capabilities',\n ),\n )\n\n server.registerPrompt(\n 'meta-usage-status',\n {\n title: 'Usage Status',\n description: \"Check the caller's public free graph_query quota.\",\n argsSchema: {},\n },\n async () => promptResult(\n 'Use Chain Insights meta_usage_status. Report the quota fields exactly as returned.',\n 'Usage status',\n ),\n )\n\n server.registerPrompt(\n 'graph-query',\n {\n title: 'Graph Query',\n description: 'Run a read-only GQL/Cypher query through the Chain Insights graph endpoint.',\n argsSchema: {\n network: NETWORK_SCHEMA,\n query: z.string().describe('Read-only GQL/Cypher query'),\n },\n },\n async ({ network, query }) => promptResult(\n [\n `Use Chain Insights graph_query on ${network} with this read-only GQL/Cypher query:`,\n '',\n '```gql',\n query,\n '```',\n '',\n 'Use USE topology for topology (address/FLOWS_TO/LINKED graph, unified recent+historical, plus the node risk_score/risk_level verdict) and USE facts for bounded TRANSFER rows and enrichment. If you need schema context, first run small discovery queries such as MATCH (a:Address) RETURN a.address AS address, keys(a) AS address_properties LIMIT 5 and MATCH (:Address)-[r:FLOWS_TO]->(:Address) RETURN keys(r) AS flow_properties LIMIT 5. Return the full address when available; never shorten addresses with ellipses.',\n ].join('\\n'),\n 'Graph query',\n ),\n )\n\n server.registerPrompt(\n 'graph-query-batch',\n {\n title: 'Graph Query Batch',\n description: 'Run related read-only GQL/Cypher queries through the Chain Insights graph endpoint in one paid batch.',\n argsSchema: {\n network: NETWORK_SCHEMA,\n queries: z.string().describe('JSON array of query objects with optional id and required query fields'),\n per_query_timeout_seconds: z.string().optional().describe('Optional integer timeout per query, 1-600 seconds'),\n },\n },\n async ({ network, queries, per_query_timeout_seconds }) => promptResult(\n [\n `Use Chain Insights graph_query_batch on ${network} with these read-only GQL/Cypher queries:`,\n '',\n '```json',\n queries,\n '```',\n per_query_timeout_seconds ? `per_query_timeout_seconds: ${per_query_timeout_seconds}` : '',\n '',\n 'Use USE topology for topology (address/FLOWS_TO/LINKED graph, unified recent+historical, plus the node risk_score/risk_level verdict) and USE facts for bounded TRANSFER rows and enrichment. If you need schema context, first run small discovery queries such as MATCH (a:Address) RETURN a.address AS address, keys(a) AS address_properties LIMIT 5 and MATCH (:Address)-[r:FLOWS_TO]->(:Address) RETURN keys(r) AS flow_properties LIMIT 5. Return the full address when available; never shorten addresses with ellipses.',\n ].filter(Boolean).join('\\n'),\n 'Graph query batch',\n ),\n )\n\n server.registerPrompt(\n 'wallet-balance',\n {\n title: 'Wallet Balance',\n description: 'Show the local Chain Insights payment wallet address, payment network, token, and amount.',\n argsSchema: {},\n },\n async () => promptResult(\n 'Use Chain Insights wallet_balance. Show the wallet address, payment network, token, and amount exactly as returned.',\n 'Wallet balance',\n ),\n )\n\n server.registerPrompt(\n 'meta-help',\n {\n title: 'Chain Insights Help',\n description: 'Show available Chain Insights tools and workspace workflow.',\n argsSchema: {},\n },\n async () => promptResult(\n 'Use Chain Insights meta_help. Summarize the available tools and workspace workflow without inventing capabilities.',\n 'Chain Insights help',\n ),\n )\n\n\n}\n\nfunction hasGraphArrayFields(value: unknown): boolean {\n if (!value || typeof value !== 'object' || Array.isArray(value)) return false\n const record = value as Record<string, unknown>\n return GRAPH_ARRAY_KEYS.some((key) => Array.isArray(record[key]))\n}\n\nfunction sanitizeStructuredContentForGraphPayload(\n structuredContent: Record<string, unknown> | undefined,\n): Record<string, unknown> | undefined {\n if (!structuredContent) return undefined\n return sanitizeStructuredValue(structuredContent) as Record<string, unknown>\n}\n\nfunction sanitizeStructuredValue(value: unknown): unknown {\n if (!value || typeof value !== 'object' || Array.isArray(value)) return value\n\n const sanitized: Record<string, unknown> = {}\n for (const [key, childValue] of Object.entries(value)) {\n if (key === 'app_data') continue\n if (GRAPH_ARRAY_KEYS.includes(key as (typeof GRAPH_ARRAY_KEYS)[number]) && Array.isArray(childValue)) {\n continue\n }\n sanitized[key] = sanitizeStructuredValue(childValue)\n }\n\n return sanitized\n}\n\nfunction getRemoteGraphPayload(result: RemoteToolResult): Record<string, unknown> | null {\n const chainInsights = result._meta?.chainInsights\n if (!chainInsights || typeof chainInsights !== 'object' || Array.isArray(chainInsights)) return null\n const graph = (chainInsights as Record<string, unknown>).graph\n if (graph === undefined) return null\n if (!graph || typeof graph !== 'object' || Array.isArray(graph)) {\n throw new Error('Invalid remote graph payload')\n }\n\n const graphRecord = graph as Record<string, unknown>\n if (!('data' in graphRecord)) {\n if ('url' in graphRecord || hasGraphArrayFields(graphRecord)) {\n throw new Error('Invalid remote graph payload')\n }\n return null\n }\n\n const data = graphRecord.data\n if (!data || typeof data !== 'object' || Array.isArray(data)) {\n throw new Error('Invalid remote graph payload')\n }\n\n return data as Record<string, unknown>\n}\n\nasync function normalizeRemoteToolResult(\n result: RemoteToolResult,\n config: Pick<InvestigatorConfig, 'dataDir' | 'serverPort'>,\n toolName = 'remote-graph',\n includeAttachments = true,\n) {\n const graphPayload = getRemoteGraphPayload(result)\n const meta = { ...(result._meta ?? {}) }\n\n if (graphPayload && includeAttachments) {\n const { writeGraphReport } = await import('./graph-reports.js')\n const { ensureArtifactServer } = await import('./artifact-server.js')\n const report = await writeGraphReport(graphPayload as never, {\n serverPort: config.serverPort,\n slug: toolName || 'remote-graph',\n })\n await ensureArtifactServer(config.serverPort)\n meta.chainInsights = {\n ...((meta.chainInsights as Record<string, unknown>) ?? {}),\n graph: {\n schema: report.schema,\n url: report.url,\n },\n }\n }\n\n return {\n content: result.content ?? [],\n structuredContent: sanitizeStructuredContentForGraphPayload(result.structuredContent),\n _meta: Object.keys(meta).length > 0 ? meta : undefined,\n isError: result.isError,\n }\n}\n\nfunction shouldIncludeAttachments(args: Record<string, unknown>, workspaceArtifactsEnabled: boolean): boolean {\n return workspaceArtifactsEnabled && args['include_attachments'] !== false\n}\n\nasync function writeLocalGraphMeta(\n graphData: unknown,\n config: Pick<InvestigatorConfig, 'dataDir' | 'serverPort'>,\n slug: string,\n includeAttachments: boolean,\n): Promise<ChainInsightsGraphMeta | undefined> {\n if (!includeAttachments) return undefined\n const { writeGraphReport } = await import('./graph-reports.js')\n const { ensureArtifactServer } = await import('./artifact-server.js')\n const report = await writeGraphReport(graphData as never, {\n serverPort: config.serverPort,\n slug,\n })\n await ensureArtifactServer(config.serverPort)\n return {\n schema: report.schema,\n url: report.url,\n }\n}\n\nfunction graphMetaResult(graph: ChainInsightsGraphMeta | undefined): Record<string, unknown> | undefined {\n return graph\n ? {\n chainInsights: {\n graph,\n },\n }\n : undefined\n}\n\nfunction cleanNetworkCapabilities(value: unknown) {\n const structuredContent = isRecord(value) ? value.structuredContent : undefined\n const facts = isRecord(structuredContent) ? structuredContent.facts : undefined\n const capabilities = isRecord(facts) ? facts.capabilities : undefined\n const networks = isRecord(capabilities) && Array.isArray(capabilities.networks)\n ? capabilities.networks\n : []\n\n return {\n schema: 'chain-insights.result.v1' as const,\n tool: 'meta_network_capabilities',\n hint: null,\n facts: {\n capabilities: mirrorGraphNetworkCapabilities({ networks }),\n },\n }\n}\n\nfunction jsonTextResult(structuredContent: Record<string, unknown>) {\n return {\n content: [{ type: 'text' as const, text: JSON.stringify(structuredContent, null, 2) }],\n structuredContent,\n isError: false,\n }\n}\n\n/**\n * Core proxy logic — exported so tests can inject dependencies directly.\n * The IIFE at the bottom calls this with real dependencies.\n *\n * stdout purity: NEVER write to stdout in this file. Use console.error() or process.stderr.write() only.\n * All diagnostic output goes to console.error() or process.stderr.write().\n */\nexport async function createProxy(): Promise<void> {\n // Lazy imports to avoid module-load side effects (critical for stdio proxy)\n const { loadConfig } = await import('../config/index.js')\n const { activeDataDir, findActiveWorkspace } = await import('../workspace/active.js')\n const { createConfiguredGraphMcpFetch, resolveGraphMcpEndpoint } = await import('./client.js')\n const { loadSchema, saveSchema } = await import('./schema-cache.js')\n\n const proxyMode = resolveMcpProxyMode()\n const workspaceArtifactsEnabled = proxyMode === 'workspace'\n const loadedConfig = await loadConfig()\n const activeWorkspace = workspaceArtifactsEnabled ? findActiveWorkspace() : null\n const config = {\n ...loadedConfig,\n dataDir: workspaceArtifactsEnabled ? activeDataDir(loadedConfig.dataDir) : loadedConfig.dataDir,\n }\n const logger = createMcpLogger(config)\n await logger.info('proxy.start', {\n data_dir: config.dataDir,\n workspace_root: activeWorkspace?.root,\n proxy_mode: proxyMode,\n graph_mcp_mode: config.graphMcpMode,\n graph_mcp_endpoint: resolveGraphMcpEndpoint(config),\n log_path: logger.filePath,\n })\n const graphMcpEndpoint = resolveGraphMcpEndpoint(config)\n\n // Build remote MCP client. The local Chain Insights MCP surface must still\n // start when the graph endpoint is temporarily unavailable so agents can use\n // help and wallet tools.\n const remoteClient = new Client({ name: 'chain-insights-proxy-client', version: PACKAGE_VERSION })\n let remoteConnected = false\n let remoteUnavailableMessage: string | undefined\n let mcpFetch: typeof fetch | undefined\n\n try {\n mcpFetch = await createConfiguredGraphMcpFetch(config)\n } catch (err) {\n await logger.error('remote.fetch_setup_failed', {\n endpoint: graphMcpEndpoint,\n error: errorForLog(err),\n })\n remoteUnavailableMessage = `Chain Insights Graph setup unavailable at ${graphMcpEndpoint}: ${(err as Error).message}`\n process.stderr.write(\n `Chain Insights MCP graph tools unavailable: ${remoteUnavailableMessage}. Local Chain Insights tools are still available.\\n`,\n )\n }\n\n if (mcpFetch) {\n try {\n await remoteClient.connect(\n new StreamableHTTPClientTransport(new URL(graphMcpEndpoint), { fetch: mcpFetch }),\n )\n remoteConnected = true\n await logger.info('remote.connect', {\n transport: 'streamable_http',\n endpoint: graphMcpEndpoint,\n })\n } catch {\n await logger.error('remote.connect_failed', {\n transport: 'streamable_http',\n endpoint: graphMcpEndpoint,\n })\n // StreamableHTTP failed — try SSE fallback (assumption A1 from RESEARCH.md)\n try {\n const { SSEClientTransport } = await import('@modelcontextprotocol/sdk/client/sse.js')\n await remoteClient.connect(\n new SSEClientTransport(new URL(graphMcpEndpoint), { fetch: mcpFetch }),\n )\n remoteConnected = true\n await logger.info('remote.connect', {\n transport: 'sse',\n endpoint: graphMcpEndpoint,\n })\n } catch (err2) {\n await logger.error('remote.connect_failed', {\n transport: 'sse',\n endpoint: graphMcpEndpoint,\n error: errorForLog(err2),\n })\n remoteUnavailableMessage = `Chain Insights Graph unreachable at ${graphMcpEndpoint}: ${(err2 as Error).message}`\n process.stderr.write(\n `Chain Insights MCP graph tools unavailable: ${remoteUnavailableMessage}. Local Chain Insights tools are still available.\\n`,\n )\n }\n }\n }\n if (remoteConnected) installRemoteCypherLogging(remoteClient as unknown as RemoteToolCaller, logger)\n\n // Schema cache check — skip remote listTools call on cache hit\n let tools: McpTool[] | null = await loadSchema(graphMcpEndpoint)\n\n if (!tools && remoteConnected) {\n // Cache miss — fetch tools from remote (client is already connected above)\n const result = await remoteClient.listTools()\n tools = result.tools as McpTool[]\n await saveSchema(tools, graphMcpEndpoint)\n await logger.info('schema.tools_loaded', {\n source: 'remote',\n count: tools.length,\n })\n } else if (tools) {\n await logger.info('schema.tools_loaded', {\n source: 'cache',\n count: tools.length,\n })\n } else {\n tools = fallbackGraphPrimitiveTools()\n await logger.info('schema.tools_loaded', {\n source: 'unavailable',\n count: tools.length,\n })\n }\n const remoteToolNames = new Set((tools ?? []).map((tool) => tool.name))\n\n // Build local stdio proxy server\n const server = new McpServer(\n { name: 'chain-insights', version: PACKAGE_VERSION },\n { instructions: workspaceArtifactsEnabled ? SERVER_INSTRUCTIONS : STATELESS_SERVER_INSTRUCTIONS },\n )\n installToolLogging(server, logger)\n\n if (remoteConnected) {\n try {\n await remoteClient.listPrompts()\n } catch (err) {\n await logger.error('remote.prompts_failed', {\n endpoint: graphMcpEndpoint,\n error: errorForLog(err),\n })\n process.stderr.write(\n `Chain Insights MCP remote prompt metadata unavailable at ${graphMcpEndpoint}: ${(err as Error).message}\\n`,\n )\n }\n }\n\n registerLocalPrompts(server)\n\n const caseToolError = (label: string, err: unknown) => ({\n content: [{ type: 'text' as const, text: `${label} failed: ${(err as Error).message}` }],\n isError: true,\n })\n\n const parseTags = (tags: string | string[] | undefined): string[] => {\n if (Array.isArray(tags)) return tags.map((tag) => tag.trim()).filter(Boolean)\n if (typeof tags === 'string') return tags.split(',').map((tag) => tag.trim()).filter(Boolean)\n return []\n }\n\n server.registerTool(\n 'meta_network_capabilities',\n {\n title: 'Network Capabilities',\n description: KNOWN_PUBLIC_TOOL_DESCRIPTIONS.meta_network_capabilities,\n inputSchema: EMPTY_INPUT_SCHEMA,\n annotations: {\n readOnlyHint: true,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n },\n },\n async () => {\n if (remoteConnected && remoteToolNames.has('network_capabilities')) {\n try {\n const result = await remoteClient.callTool({ name: 'network_capabilities', arguments: {} })\n return jsonTextResult(cleanNetworkCapabilities(result))\n } catch (err) {\n return {\n content: [{ type: 'text' as const, text: `Network capabilities failed: ${(err as Error).message}` }],\n isError: true,\n }\n }\n }\n return jsonTextResult(cleanNetworkCapabilities(undefined))\n },\n )\n\n server.registerTool(\n 'meta_usage_status',\n {\n title: 'Usage Status',\n description: KNOWN_PUBLIC_TOOL_DESCRIPTIONS.meta_usage_status,\n inputSchema: EMPTY_INPUT_SCHEMA,\n annotations: {\n readOnlyHint: true,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: true,\n },\n },\n async () => {\n try {\n if (!remoteConnected) {\n return {\n content: [{\n type: 'text' as const,\n text: `${remoteUnavailableMessage ?? `Chain Insights Graph is not connected at ${graphMcpEndpoint}`}. Restart the Chain Insights MCP proxy after the endpoint is reachable.`,\n }],\n isError: true,\n }\n }\n if (!remoteToolNames.has('usage_status')) {\n return jsonTextResult(primitiveBackendUsageStatus(graphMcpEndpoint))\n }\n const result = await remoteClient.callTool({ name: 'usage_status', arguments: {} }) as RemoteToolResult\n const structuredContent = isRecord(result.structuredContent)\n ? { ...result.structuredContent, tool: 'meta_usage_status' }\n : undefined\n return {\n content: structuredContent\n ? [{ type: 'text' as const, text: JSON.stringify(structuredContent, null, 2) }]\n : result.content ?? [],\n structuredContent,\n _meta: result._meta,\n isError: result.isError,\n }\n } catch (err) {\n return {\n content: [{ type: 'text' as const, text: `Usage status failed: ${(err as Error).message}` }],\n isError: true,\n }\n }\n },\n )\n\n if (workspaceArtifactsEnabled) {\n server.registerTool(\n 'wallet_balance',\n {\n title: 'Wallet Balance',\n description: KNOWN_PUBLIC_TOOL_DESCRIPTIONS.wallet_balance,\n inputSchema: EMPTY_INPUT_SCHEMA,\n annotations: {\n readOnlyHint: true,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: true,\n },\n },\n async () => {\n try {\n const { formatWalletBalanceResult, getWalletAccount, getWalletBalanceResult } = await import('../wallet/tools.js')\n const account = await getWalletAccount()\n const structuredContent = await getWalletBalanceResult(account)\n return {\n content: [{ type: 'text' as const, text: formatWalletBalanceResult(structuredContent) }],\n structuredContent: structuredContent as unknown as Record<string, unknown>,\n isError: false,\n }\n } catch (err) {\n return {\n content: [{ type: 'text' as const, text: `Balance failed: ${(err as Error).message}` }],\n isError: true,\n }\n }\n },\n )\n }\n // NOTE: only wallet_balance is workspace-only. Everything below — the graph\n // app resource, the aml_*/graph tools, and server.connect() — is shared and\n // MUST run in stateless mode too. (Regression #136: this brace had drifted to\n // the end of the function, so stateless mode skipped server.connect entirely.)\n\n registerAppResource(\n server,\n 'Fund Flow Graph',\n GRAPH_RESOURCE_URI,\n {\n description: 'Interactive fund-flow and pattern graph for Chain Insights investigation reports.',\n _meta: {\n ui: {\n csp: {\n resourceDomains: graphArtifactOrigins(config),\n connectDomains: graphArtifactOrigins(config),\n },\n },\n },\n },\n async () => ({\n contents: [\n {\n uri: GRAPH_RESOURCE_URI,\n mimeType: RESOURCE_MIME_TYPE,\n text: readGraphAppHtml(),\n _meta: {\n ui: {\n csp: {\n resourceDomains: graphArtifactOrigins(config),\n connectDomains: graphArtifactOrigins(config),\n },\n },\n },\n },\n ],\n }),\n )\n\n\n\n if (!remoteToolNames.has('aml_address_risk')) {\n registerAppTool(\n server,\n 'aml_address_risk',\n {\n title: 'Address Risk',\n description: KNOWN_PUBLIC_TOOL_DESCRIPTIONS.aml_address_risk,\n inputSchema: {\n address: z.string().min(1).describe('Blockchain address to screen'),\n network: NETWORK_SCHEMA,\n compare_address: z.string().optional().describe('Optional address to compare against the screened address'),\n include_attachments: z.boolean().optional().describe('Include graph app report metadata'),\n },\n _meta: {\n ui: {\n resourceUri: GRAPH_RESOURCE_URI,\n },\n },\n annotations: {\n readOnlyHint: true,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: true,\n },\n },\n async ({ address, network, compare_address, include_attachments }) => {\n try {\n if (!remoteConnected) {\n return {\n content: [{\n type: 'text' as const,\n text: `${remoteUnavailableMessage ?? `Chain Insights Graph is not connected at ${graphMcpEndpoint}`}. Restart the Chain Insights MCP proxy after the endpoint is reachable.`,\n }],\n isError: true,\n }\n }\n const { addressRisk } = await import('../investigation/public-tools.js')\n const result = await addressRisk(remoteClient, {\n address,\n network,\n compareAddress: compare_address,\n writeArtifacts: workspaceArtifactsEnabled,\n })\n const graph = await writeLocalGraphMeta(\n result.graphData,\n config,\n `address-risk-${network}-${address}`,\n shouldIncludeAttachments({ include_attachments }, workspaceArtifactsEnabled),\n )\n return {\n content: [{ type: 'text' as const, text: result.summaryText }],\n structuredContent: result.structuredContent,\n _meta: graphMetaResult(graph),\n isError: false,\n }\n } catch (err) {\n if (err instanceof PaymentRequiredError) {\n return { content: [{ type: 'text' as const, text: err.message }], isError: true }\n }\n return {\n content: [{ type: 'text' as const, text: `Address risk failed: ${(err as Error).message}` }],\n isError: true,\n }\n }\n },\n )\n }\n\n server.registerTool(\n 'meta_help',\n {\n title: 'Chain Insights Help',\n description: KNOWN_PUBLIC_TOOL_DESCRIPTIONS.meta_help,\n inputSchema: EMPTY_INPUT_SCHEMA,\n annotations: {\n readOnlyHint: true,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n },\n },\n async () => ({\n content: [\n {\n type: 'text' as const,\n text: workspaceArtifactsEnabled\n ? [\n 'Chain Insights helps AI agents run AML investigation workflows and keep evidence in local workspace files.',\n '',\n CHAIN_INSIGHTS_WORKFLOW,\n '',\n 'Investigation tools:',\n '- meta_network_capabilities: inspect supported networks and available tools.',\n '- meta_usage_status: check the caller public free graph_query quota.',\n '- aml_address_risk: screen one blockchain address; optionally compare it with another address.',\n '- graph_query: run read-only GQL/Cypher through the universal graph endpoint. Use USE topology or USE facts.',\n '- graph_query_batch: run related read-only graph-language queries through one paid graph call.',\n '',\n 'Wallet tools:',\n '- wallet_balance: show the local payment wallet address, payment network, token, and amount.',\n '- meta_help: show this overview.',\n '',\n GRAPH_REPORT_HINTS,\n ].join('\\n')\n : [\n 'Chain Insights stateless AML proxy for host applications.',\n '',\n 'Local workspace persistence, wallet, and graph report attachment tools are disabled in this mode.',\n '',\n 'Available graph-backed tools:',\n '- meta_network_capabilities: inspect supported networks and available tools.',\n '- meta_usage_status: check the caller public free graph_query quota.',\n '- aml_address_risk: screen one blockchain address; optionally compare it with another address.',\n '- graph_query: run read-only GQL/Cypher through the universal graph endpoint. Use USE topology or USE facts.',\n '- graph_query_batch: run related read-only graph-language queries through one paid graph call.',\n ].join('\\n'),\n },\n ],\n isError: false,\n }),\n )\n\n // Register each remote tool locally — passthrough proxy pattern\n for (const tool of tools ?? []) {\n if (HIDDEN_REMOTE_TOOL_NAMES.has(tool.name)) continue\n if (LOCAL_TOOL_NAMES.has(tool.name)) continue\n const inputSchema = knownPublicToolInputSchema(tool.name) ?? z.object({}).passthrough()\n const handler = async (args: unknown) => {\n try {\n if (!remoteConnected) {\n return {\n content: [{\n type: 'text' as const,\n text: `${remoteUnavailableMessage ?? `Chain Insights Graph is not connected at ${graphMcpEndpoint}`}. Restart the Chain Insights MCP proxy after the endpoint is reachable.`,\n }],\n isError: true,\n }\n }\n const normalizedArgs = normalizeRemoteToolArguments(tool.name, args)\n const validationError = validateKnownPublicToolArguments(tool.name, normalizedArgs)\n if (validationError) {\n return {\n content: [{ type: 'text' as const, text: validationError }],\n isError: true,\n }\n }\n const request = {\n name: tool.name,\n arguments: normalizedArgs,\n }\n const requestOptions = remoteToolRequestOptions(tool.name)\n const result = requestOptions\n ? await remoteClient.callTool(request, undefined, requestOptions)\n : await remoteClient.callTool(request)\n return await normalizeRemoteToolResult(\n result as RemoteToolResult,\n config,\n tool.name,\n shouldIncludeAttachments(normalizedArgs, workspaceArtifactsEnabled),\n )\n } catch (err) {\n if (err instanceof PaymentRequiredError) {\n return {\n content: [{ type: 'text' as const, text: err.message }],\n isError: true,\n }\n }\n const msg = (err as Error).message ?? String(err)\n const isTransport402 = /\\b402\\b/.test(msg) || msg.toLowerCase().includes('payment')\n if (isTransport402) {\n return {\n content: [{\n type: 'text' as const,\n text: `Payment required for ${tool.name}. This tool costs USDC on Base via x402 micropayments. ` +\n 'Next steps: run `chain-insights wallet ready` to check funding and finish one-time payment setup, ' +\n 'run `chain-insights wallet topup` if it says the wallet needs USDC, ' +\n 'or `chain-insights access-key set <key>` if you have been given test access.',\n }],\n isError: true,\n }\n }\n return {\n content: [{ type: 'text' as const, text: `MCP call failed: ${msg}` }],\n isError: true,\n }\n }\n }\n const toolConfig = {\n title: tool.title,\n description: claudeFacingToolDescription(tool),\n inputSchema,\n ...(knownPublicToolAnnotations(tool.name) ? { annotations: knownPublicToolAnnotations(tool.name) } : {}),\n }\n\n if (hasGraphApp(tool)) {\n registerAppTool(\n server,\n tool.name,\n {\n ...toolConfig,\n _meta: graphToolMeta(tool),\n },\n handler,\n )\n } else {\n server.registerTool(tool.name, toolConfig, handler)\n }\n }\n\n // Connect to stdio transport — after this line, stdout belongs to MCP\n const transport = new StdioServerTransport()\n await server.connect(transport)\n await logger.info('proxy.ready', {\n tools: [\n ...LOCAL_TOOL_NAMES,\n ...(tools ?? []).map((tool) => tool.name).filter((name) => !HIDDEN_REMOTE_TOOL_NAMES.has(name) && !LOCAL_TOOL_NAMES.has(name)),\n ].length,\n })\n\n // Signal handling — clean shutdown\n const shutdown = async () => {\n await logger.info('proxy.shutdown')\n transport.close()\n process.exit(0)\n }\n process.on('SIGINT', () => { void shutdown() })\n process.on('SIGTERM', () => { void shutdown() })\n}\n\n\n// Entry point — only execute when run as the main module (not when imported by tests)\n// Using process.argv check to detect direct execution vs import\nif (process.argv[1] && import.meta.url.includes(process.argv[1].replace(/\\\\/g, '/'))) {\n createProxy().catch((err) => {\n process.stderr.write(`Chain Insights MCP proxy startup failed: ${(err as Error).message}\\n`)\n process.exit(1)\n })\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAoBA,MAAM,mCAAmB,IAAI,IAAI;CAC/B;CACA;CACA;CACA;AACF,CAAC;AACD,MAAM,qBAAqB;AAC3B,MAAM,uCAAuB,IAAI,IAAI,CACnC,kBACF,CAAC;AACD,MAAM,mBAAmB;CAAC;CAAS;CAAS;CAAS;AAAc;AACnE,MAAM,YAAY,KAAK,QAAQ,cAAc,OAAO,KAAK,GAAG,CAAC;AAI7D,SAAgB,oBAAoB,MAAyB,QAAQ,KAAmB;CACtF,MAAM,MAAM,IAAI,gCAAgC,EAAE,KAAK,CAAC,CAAC,YAAY;CACrE,IAAI,CAAC,OAAO,QAAQ,aAAa,OAAO;CACxC,IAAI,QAAQ,eAAe,QAAQ,kBAAkB,QAAQ,kBAAkB,OAAO;CACtF,MAAM,IAAI,MAAM,sEAAsE,IAAI,EAAE;AAC9F;AAEA,MAAM,iCAAyD;CAC7D,2BAA2B;CAC3B,mBAAmB;CACnB,WAAW;CACX,gBAAgB;CAChB,kBAAkB;CAClB,aAAa;CACb,mBAAmB;AACrB;AACA,MAAM,sCAAsC,CAAC,eAAe,mBAAmB;AAe/E,MAAM,iBAAiB,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,SAAS,kIAAmB;AAErE,MAAM,qBAAqB,EAAE,aAAa,CAAC,CAAC;AAC5C,MAAM,uCAAuC,MAAU;AAEvD,MAAM,0BAA0B;CAC9B;CACA;CACA;CACA;CACA;CACA;AACF,CAAC,CAAC,KAAK,IAAI;AAEX,MAAM,qBAAqB;CACzB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;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AAC;KACpE,SAAS;IACX;GACF;EACF;EACA,MAAM,aAAa;GACjB,OAAO,KAAK;GACZ,aAAa,4BAA4B,IAAI;GAC7C;GACA,GAAI,2BAA2B,KAAK,IAAI,IAAI,EAAE,aAAa,2BAA2B,KAAK,IAAI,EAAE,IAAI,CAAC;EACxG;EAEA,IAAI,YAAY,IAAI,GAClB,gBACE,QACA,KAAK,MACL;GACE,GAAG;GACH,OAAO,cAAc,IAAI;EAC3B,GACA,OACF;OAEA,OAAO,aAAa,KAAK,MAAM,YAAY,OAAO;CAEtD;CAGA,MAAM,YAAY,IAAI,qBAAqB;CAC3C,MAAM,OAAO,QAAQ,SAAS;CAC9B,MAAM,OAAO,KAAK,eAAe,EAC/B,OAAO,CACL,GAAG,kBACH,IAAI,SAAS,CAAC,EAAA,CAAG,KAAK,SAAS,KAAK,IAAI,CAAC,CAAC,QAAQ,SAAS,CAAC,yBAAyB,IAAI,IAAI,KAAK,CAAC,iBAAiB,IAAI,IAAI,CAAC,CAC/H,CAAC,CAAC,OACJ,CAAC;CAGD,MAAM,WAAW,YAAY;EAC3B,MAAM,OAAO,KAAK,gBAAgB;EAClC,UAAU,MAAM;EAChB,QAAQ,KAAK,CAAC;CAChB;CACA,QAAQ,GAAG,gBAAgB;EAAE,SAAc;CAAE,CAAC;CAC9C,QAAQ,GAAG,iBAAiB;EAAE,SAAc;CAAE,CAAC;AACjD;AAKA,IAAI,QAAQ,KAAK,MAAM,OAAO,KAAK,IAAI,SAAS,QAAQ,KAAK,EAAE,CAAC,QAAQ,OAAO,GAAG,CAAC,GACjF,YAAY,CAAC,CAAC,OAAO,QAAQ;CAC3B,QAAQ,OAAO,MAAM,4CAA6C,IAAc,QAAQ,GAAG;CAC3F,QAAQ,KAAK,CAAC;AAChB,CAAC"}
1
+ {"version":3,"file":"mcp-proxy.mjs","names":[],"sources":["../src/mcp/proxy.ts"],"sourcesContent":["import { readFileSync } from 'node:fs'\nimport { appendFile, mkdir } from 'node:fs/promises'\nimport path from 'node:path'\nimport { fileURLToPath } from 'node:url'\nimport { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'\nimport { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'\nimport { Client } from '@modelcontextprotocol/sdk/client/index.js'\nimport { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js'\nimport type { ContentBlock, GetPromptResult } from '@modelcontextprotocol/sdk/types.js'\nimport {\n registerAppResource,\n registerAppTool,\n RESOURCE_MIME_TYPE,\n} from '@modelcontextprotocol/ext-apps/server'\nimport * as z from 'zod'\nimport type { InvestigatorConfig } from '../config/schema.js'\nimport { PACKAGE_VERSION } from '../version.js'\nimport type { McpTool } from './schema-cache.js'\nimport {\n HIDDEN_REMOTE_TOOL_NAMES,\n PUBLIC_MCP_TOOL_ALLOWED_ARGS,\n PUBLIC_MCP_TOOL_REQUIRED_ARGS,\n} from './tool-visibility.js'\nimport { PaymentRequiredError } from './client.js'\nimport { primitiveBackendUsageStatus } from './usage-status.js'\nimport { mirrorGraphNetworkCapabilities } from './capabilities.js'\nimport { actionLogSignalsFromResult, appendActionLog } from './action-log.js'\n\nconst LOCAL_TOOL_NAMES = new Set([\n 'meta_network_capabilities',\n 'meta_usage_status',\n 'meta_help',\n 'wallet_balance',\n])\nconst GRAPH_RESOURCE_URI = 'ui://chain-insights/graph'\nconst GRAPH_APP_TOOL_NAMES = new Set(['aml_address_risk'])\nconst GRAPH_ARRAY_KEYS = ['nodes', 'edges', 'flows', 'edge_anchors'] as const\nconst __dirname = path.dirname(fileURLToPath(import.meta.url))\n\nexport type McpProxyMode = 'workspace' | 'stateless'\n\nexport function resolveMcpProxyMode(env: NodeJS.ProcessEnv = process.env): McpProxyMode {\n const raw = env['CHAIN_INSIGHTS_MCP_PROXY_MODE']?.trim().toLowerCase()\n if (!raw || raw === 'workspace') return 'workspace'\n if (raw === 'stateless' || raw === 'no-workspace' || raw === 'workspace-less') return 'stateless'\n throw new Error(`CHAIN_INSIGHTS_MCP_PROXY_MODE must be workspace or stateless; got \"${raw}\"`)\n}\n\nconst KNOWN_PUBLIC_TOOL_DESCRIPTIONS: Record<string, string> = {\n meta_network_capabilities: 'Return the current Chain Insights network and tool support matrix.',\n meta_usage_status: \"Return the caller's public free graph_query quota for the current UTC day.\",\n meta_help: 'Show a short guide to Chain Insights tools and workflow.',\n wallet_balance:\n 'Show the local Chain Insights payment wallet address, payment network, token, and amount.',\n aml_address_risk:\n 'Screen one blockchain address for AML risk, behavior patterns, neighborhood context, exchange exposure, and optional comparison with another address. Topology reads cover full lifetime history in one unified graph.',\n graph_query:\n 'Run a read-only GQL/Cypher query through the Chain Insights graph endpoint. Use USE topology for topology (address/FLOWS_TO/LINKED graph, unified recent+historical, plus the node risk_score/risk_level verdict) and USE facts for bounded TRANSFER rows and enrichment. Preserve full addresses exactly.',\n graph_query_batch:\n 'Run multiple read-only GQL/Cypher queries through the Chain Insights graph endpoint in one paid batch. Prefer this for related topology/facts reads.',\n}\nconst FALLBACK_GRAPH_PRIMITIVE_TOOL_NAMES = ['graph_query', 'graph_query_batch'] as const\n\ntype ToolInputShape = Record<string, z.ZodTypeAny>\ntype ToolHandler = (args: unknown, extra?: unknown) => Promise<unknown> | unknown\ntype ToolRegistrationConfig = Parameters<McpServer['registerTool']>[1]\ntype ToolCallInput = { name: string; arguments?: Record<string, unknown> }\ntype RemoteToolCaller = {\n callTool: Client['callTool']\n}\ntype ChainInsightsGraphMeta = {\n schema: string\n url: string\n}\n\nconst NETWORK_DESCRIPTION =\n 'Network to query. Call meta_network_capabilities first and pass a name GraphRAG advertised. CIA does not pick a default network.'\nconst NETWORK_SCHEMA = z.string().min(1).describe(NETWORK_DESCRIPTION)\n\nconst EMPTY_INPUT_SCHEMA = z.strictObject({})\nconst REMOTE_GRAPH_TOOL_REQUEST_TIMEOUT_MS = 15 * 60 * 1000\n\nconst CHAIN_INSIGHTS_WORKFLOW = [\n 'Workflow:',\n '1. Chain Insights workspaces are append-only local working directories. Bootstrap with cia init before workflows that persist artifacts.',\n '2. Do not call investigation tools until required arguments are known. Network is required; use meta_network_capabilities to check supported networks and available tools, or ask the user if missing.',\n '3. Use aml_address_risk for single-address enrichment. Use graph_query(_batch) for graph-level questions that aml_address_risk does not answer.',\n '4. Persisted outputs belong in the initialized workspace under reports/, reports/graphs/, reports/tables/, artifacts/, entities/, sessions/, and published/.',\n '5. For local review, inspect the generated Markdown and graph/table artifacts directly in the workspace.',\n].join('\\n')\n\nconst GRAPH_SCHEMA_HINTS = [\n 'Graph query hints:',\n '- Call meta_network_capabilities first. Pass network= exactly as GraphRAG advertised it. CIA does not pick a default network.',\n '- The graph is address-grain. The only topology money node label is Address, keyed by the raw chain-native H160 address on EVM networks, for example 0x1874a43d7c6d888f9eda3d22a3a49704e3cadb24. The network value on Address nodes matches the tool argument. There is no separate identity key.',\n '- Address nodes carry address, network, labels, and is_exchange. (:Address)-[:LINKED]-(:Address) is an undirected ownership-overlay edge (basis derived/associated, plus confidence, source_event, declared_owner) asserting the two addresses are controlled by the same actor. LINKED is served on the topology graph only. Enumerate LINKED neighbors with MATCH (a:Address {address: $addr})-[l:LINKED]-(b:Address) RETURN b.address, b.network, l.basis, l.confidence.',\n '- Address nodes also carry a risk verdict (risk_score float, risk_level string) plus base activity rollups: degree_in/degree_out/degree_total (distinct counterparty addresses), tx_in_count/tx_out_count/tx_total_count, total_in_usd/total_out_usd/total_volume_usd, net_flow_usd (in minus out; positive = net receiver) — all computed from external flows only — and first_activity_timestamp/last_activity_timestamp/activity_span_days, which include all flows (self-loops included). FLOWS_TO edges carry tx_count, amount_usd_sum, avg_tx_size_usd (understates when price_coverage_ratio < 1), first/last_seen_timestamp, first/last_tx_id, price_coverage_ratio. Lifetime aggregates are the only serving window.',\n '- For actor-level exposure (AC11), UNION FLOWS_TO reachability over one visible LINKED hop instead of expanding through the LINKED edge itself: MATCH (a:Address {address: $addr})-[:LINKED]-(owned:Address)-[r:FLOWS_TO]-(b:Address) WHERE owned.address <> b.address AND a.address <> b.address RETURN owned.address, b.address, r.amount_usd_sum.',\n '- The risk verdict lives on topology nodes (risk_score float, risk_level string). Labels and per-label risk also live on the address node (labels array + label_risk entries: label, risk_level, updated_timestamp). USE facts serves bounded individual transfer rows (TRANSFER edges) only; lifetime address metrics (degrees, totals, activity window) are node properties on USE topology.',\n '- (from:Address)-[t:TRANSFER]->(to:Address) on USE facts returns individual transfer rows, not aggregates, with properties amount, amount_usd, asset_symbol, asset_contract, tx_id, block_height, block_timestamp, event_index, edge_index, price_usd, and price_missing. Every TRANSFER query — row-select or count()/sum() aggregate — requires an indexed predicate: address equality on either endpoint (for example {address: \"...\"} on from or to) or a WHERE t.tx_id = \"...\" equality; a bare LIMIT with no indexed predicate is rejected, since facts_transfers_view is a full transfer-history table, not a small per-address dimension view.',\n '- Facts graph labels include Address; the TRANSFER relationship connects two Address nodes. Facts address keys match topology address values exactly.',\n '- Topology relationships include FLOWS_TO, LINKED, and RISK_PROXIMITY between Address nodes.',\n '- FLOWS_TO properties commonly carry tx_count, amount_usd_sum, avg_tx_size_usd, first_seen_timestamp, last_seen_timestamp, first_tx_id, last_tx_id, price_coverage_ratio. Confirm available fields through runtime schema before relying on them.',\n '- Traversal rule: for BFS, fixed-hop fallback, shortest-path, or manual FLOWS_TO traversal, exchange hot wallets are terminal endpoints only. Do not expand from, through, or classify exchange nodes as deposit, suspect, or intermediate candidates; filter every non-terminal node with is_exchange IS NULL.',\n '- Start schema discovery with endpoint-safe property reads: MATCH (n:Address) WHERE n.address IS NOT NULL RETURN n.address AS address, n.network AS network, n.labels AS labels, n.risk_score AS risk_score, n.risk_level AS risk_level LIMIT 20',\n '- Relationship discovery: MATCH (:Address)-[r:FLOWS_TO]->(:Address) RETURN r.amount_usd_sum AS amount_usd_sum, r.tx_count AS tx_count LIMIT 20',\n '- graph_query uses the active Chain Insights graph endpoint. Select the graph with USE topology for topology (address/FLOWS_TO/LINKED graph, unified recent+historical, plus the node risk_score/risk_level verdict) and USE facts for bounded TRANSFER rows and enrichment; address is the node grain, not the topology name.',\n '- All graph_query calls are read-only. Never use CREATE, INSERT, MERGE, SET, DELETE, REMOVE, DROP, DETACH, ADD, CONNECT, DISCONNECT, ALTER, TRUNCATE, GRANT, or REVOKE.',\n '- Use USE facts graph patterns for fact and enrichment reads. Do not query internal table namespaces directly.',\n].join('\\n')\n\nconst GRAPH_REPORT_HINTS = [\n 'Graph visualization behavior:',\n '- Graph-backed tools return the investigator report as text content and keep raw graph data out of LLM-visible structuredContent.',\n '- Chain Insights prepares the graph view automatically from local workspace report files when graph metadata is available.',\n '- If the graph view cannot load a report, retry the graph-backed tool call so Chain Insights can recreate the local graph report.',\n].join('\\n')\n\nconst SERVER_INSTRUCTIONS = [\n 'Chain Insights is a local graph-analysis workspace for AI agents.',\n CHAIN_INSIGHTS_WORKFLOW,\n GRAPH_REPORT_HINTS,\n GRAPH_SCHEMA_HINTS,\n 'Presentation rules: preserve tool summaries as returned; never truncate blockchain addresses or identity_resolution audit mappings.',\n].join('\\n\\n')\n\nconst STATELESS_SERVER_INSTRUCTIONS = [\n 'Chain Insights is running as a stateless AML proxy for a host application.',\n 'Do not use local workspace persistence, wallet, or graph report workflows in this mode.',\n 'Use meta_network_capabilities first when network support is unknown, then call aml_address_risk, graph_query, or graph_query_batch as needed.',\n GRAPH_SCHEMA_HINTS,\n 'Presentation rules: preserve tool summaries as returned; never truncate blockchain addresses or identity_resolution audit mappings.',\n].join('\\n\\n')\n\nfunction readGraphAppHtml(): string {\n const candidates = [\n path.resolve(__dirname, 'templates', 'graph.html'),\n path.resolve(__dirname, '..', 'templates', 'graph.html'),\n path.resolve(__dirname, '..', 'viz', 'templates', 'graph.html'),\n ]\n\n for (const candidate of candidates) {\n try {\n return readFileSync(candidate, 'utf8')\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code !== 'ENOENT') throw err\n }\n }\n\n throw new Error(`Chain Insights Graph app template not found. Tried: ${candidates.join(', ')}`)\n}\n\nfunction graphArtifactOrigins(config: Pick<InvestigatorConfig, 'serverPort'>): string[] {\n return [`http://127.0.0.1:${config.serverPort}`, `http://localhost:${config.serverPort}`]\n}\n\nfunction hasGraphApp(tool: McpTool): boolean {\n const configuredUri = tool._meta?.ui\n if (\n configuredUri &&\n typeof configuredUri === 'object' &&\n 'resourceUri' in configuredUri &&\n configuredUri.resourceUri === GRAPH_RESOURCE_URI\n ) {\n return true\n }\n\n if (tool._meta?.['ui/resourceUri'] === GRAPH_RESOURCE_URI) return true\n if (GRAPH_APP_TOOL_NAMES.has(tool.name)) return true\n return JSON.stringify(tool.outputSchema ?? {}).includes('\"app_data\"')\n}\n\nfunction graphToolMeta(tool: McpTool): Record<string, unknown> & { ui: { resourceUri: string } } {\n const meta = { ...(tool._meta ?? {}) }\n const ui =\n meta.ui && typeof meta.ui === 'object' && !Array.isArray(meta.ui)\n ? { ...(meta.ui as Record<string, unknown>) }\n : {}\n\n return {\n ...meta,\n ui: {\n ...ui,\n resourceUri: GRAPH_RESOURCE_URI,\n },\n }\n}\n\n// Exported so a test can prove, for EVERY public tool, that each declared\n// schema argument also appears in PUBLIC_MCP_TOOL_ALLOWED_ARGS. An argument\n// present here but missing there is silently stripped by\n// normalizeRemoteToolArguments and the caller never learns their override was\n// ignored — the failure mode that shipped with `time_scope`.\nexport function knownPublicToolInputSchema(toolName: string): ToolInputShape | null {\n switch (toolName) {\n case 'aml_address_risk':\n return {\n address: z.string().min(1).describe('Blockchain address to screen.'),\n network: NETWORK_SCHEMA,\n compare_address: z\n .string()\n .optional()\n .describe('Optional address to compare against the screened address.'),\n include_attachments: z.boolean().optional().describe('Include graph app report metadata'),\n }\n case 'graph_query':\n return {\n query: z\n .string()\n .min(1)\n .describe(\n 'Read-only GQL/Cypher query. Use USE topology for topology (address/FLOWS_TO/LINKED graph, unified recent+historical, plus the node risk_score/risk_level verdict) and USE facts for bounded TRANSFER rows and enrichment.'\n ),\n network: NETWORK_SCHEMA,\n }\n case 'graph_query_batch':\n return {\n network: NETWORK_SCHEMA,\n queries: z\n .array(\n z.object({\n id: z.string().optional(),\n query: z.string().min(1).describe('Read-only GQL/Cypher query'),\n })\n )\n .min(1)\n .max(20),\n per_query_timeout_seconds: z.number().int().min(1).max(600).optional(),\n }\n default:\n return null\n }\n}\n\nfunction fallbackGraphPrimitiveTools(): McpTool[] {\n return FALLBACK_GRAPH_PRIMITIVE_TOOL_NAMES.map((name) => ({\n name,\n description: KNOWN_PUBLIC_TOOL_DESCRIPTIONS[name],\n }))\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return !!value && typeof value === 'object' && !Array.isArray(value)\n}\n\nfunction redactLogValue(value: unknown): unknown {\n if (Array.isArray(value)) return value.map(redactLogValue)\n if (!isRecord(value)) return value\n return Object.fromEntries(\n Object.entries(value).map(([key, entry]) => {\n if (/token|secret|password|private.?key|authorization/i.test(key)) return [key, '[redacted]']\n return [key, redactLogValue(entry)]\n })\n )\n}\n\nfunction errorForLog(err: unknown): Record<string, unknown> {\n const error = err as Error\n return {\n name: error.name ?? 'Error',\n message: error.message ?? String(err),\n }\n}\n\nfunction sanitizeCypher(query: string): string {\n return query.replace(/\\s+/g, ' ').trim()\n}\n\nfunction cypherLogPayload(tool: string, args: unknown): Record<string, unknown> | null {\n if (!isRecord(args)) return null\n if (tool === 'graph_query') {\n return {\n network: args.network,\n queries: [\n {\n id: tool,\n query: typeof args.query === 'string' ? sanitizeCypher(args.query) : args.query,\n },\n ],\n }\n }\n if (tool === 'graph_query_batch') {\n const queries = Array.isArray(args.queries) ? args.queries : []\n return {\n network: args.network,\n per_query_timeout_seconds: args.per_query_timeout_seconds,\n query_count: queries.length,\n queries: queries.map((entry, index) =>\n isRecord(entry)\n ? {\n id: typeof entry.id === 'string' ? entry.id : `q${index + 1}`,\n query: typeof entry.query === 'string' ? sanitizeCypher(entry.query) : entry.query,\n }\n : { id: `q${index + 1}`, query: entry }\n ),\n }\n }\n return null\n}\n\nfunction createMcpLogger(config: Pick<InvestigatorConfig, 'dataDir'>) {\n const disabled = process.env.CHAIN_INSIGHTS_MCP_LOG === '0'\n const filePath =\n process.env.CHAIN_INSIGHTS_MCP_LOG_PATH?.trim() ||\n path.join(config.dataDir, '.chain-insights', 'runtime', 'logs', 'mcp-proxy.jsonl')\n\n async function write(\n level: 'info' | 'error',\n event: string,\n fields: Record<string, unknown> = {}\n ): Promise<void> {\n if (disabled) return\n try {\n await mkdir(path.dirname(filePath), { recursive: true })\n await appendFile(\n filePath,\n JSON.stringify({\n ts: new Date().toISOString(),\n level,\n event,\n pid: process.pid,\n ...fields,\n }) + '\\n',\n { mode: 0o600 }\n )\n } catch {\n // Logging must never break the stdio MCP server.\n }\n }\n\n return {\n filePath,\n info: (event: string, fields?: Record<string, unknown>) => write('info', event, fields),\n error: (event: string, fields?: Record<string, unknown>) => write('error', event, fields),\n }\n}\n\nfunction installToolLogging(server: McpServer, logger: ReturnType<typeof createMcpLogger>): void {\n const existingRegisterTool = server.registerTool\n const originalRegisterTool = existingRegisterTool.bind(server)\n const wrappedRegisterTool = ((\n name: string,\n config: ToolRegistrationConfig,\n handler: ToolHandler\n ) => {\n const wrapped: ToolHandler = async (args, extra) => {\n const startedAt = Date.now()\n await logger.info('tool.start', {\n tool: name,\n args: redactLogValue(args),\n })\n try {\n const result = await handler(args, extra)\n const isError = isRecord(result) && result.isError === true\n await logger.info('tool.end', {\n tool: name,\n duration_ms: Date.now() - startedAt,\n is_error: isError,\n })\n return result\n } catch (err) {\n await logger.error('tool.throw', {\n tool: name,\n duration_ms: Date.now() - startedAt,\n error: errorForLog(err),\n })\n throw err\n }\n }\n return originalRegisterTool(name, config, wrapped as never)\n }) as typeof server.registerTool\n Object.assign(wrappedRegisterTool, existingRegisterTool)\n server.registerTool = wrappedRegisterTool\n}\n\nfunction installRemoteCypherLogging(\n remoteClient: RemoteToolCaller,\n logger: ReturnType<typeof createMcpLogger>\n): void {\n const existingCallTool = remoteClient.callTool\n const originalCallTool = existingCallTool.bind(remoteClient)\n const wrappedCallTool = (async (...args: Parameters<Client['callTool']>) => {\n const input = args[0] as ToolCallInput\n const queryPayload = cypherLogPayload(input.name, input.arguments)\n const toolArgs = input.arguments ?? {}\n const startedAt = Date.now()\n if (queryPayload) {\n await logger.info('topology.start', {\n tool: input.name,\n ...queryPayload,\n })\n }\n try {\n const result = await originalCallTool(...args)\n if (queryPayload) {\n await logger.info('topology.end', {\n tool: input.name,\n duration_ms: Date.now() - startedAt,\n is_error: isRecord(result) && result.isError === true,\n })\n }\n const { warnings, search_limits } = actionLogSignalsFromResult(result)\n await appendActionLog({\n timestamp: startedAt,\n tool: input.name,\n args: toolArgs,\n outcome: 'ok',\n duration_ms: Date.now() - startedAt,\n warnings,\n search_limits,\n })\n return result\n } catch (err) {\n if (queryPayload) {\n await logger.error('cypher.throw', {\n tool: input.name,\n duration_ms: Date.now() - startedAt,\n error: errorForLog(err),\n })\n }\n await appendActionLog({\n timestamp: startedAt,\n tool: input.name,\n args: toolArgs,\n outcome: 'error',\n duration_ms: Date.now() - startedAt,\n error: (err as Error).message,\n })\n throw err\n }\n }) as typeof remoteClient.callTool\n Object.assign(wrappedCallTool, existingCallTool)\n remoteClient.callTool = wrappedCallTool\n}\n\nfunction remoteToolRequestOptions(toolName: string): Parameters<Client['callTool']>[2] | undefined {\n if (toolName === 'graph_query' || toolName === 'graph_query_batch') {\n return {\n timeout: REMOTE_GRAPH_TOOL_REQUEST_TIMEOUT_MS,\n maxTotalTimeout: REMOTE_GRAPH_TOOL_REQUEST_TIMEOUT_MS,\n }\n }\n return undefined\n}\n\nfunction isBlankArgument(value: unknown): boolean {\n if (value === undefined || value === null) return true\n if (typeof value === 'string') return value.trim() === ''\n if (Array.isArray(value)) return value.length === 0 || value.every(isBlankArgument)\n return false\n}\n\nfunction normalizeRemoteToolArguments(toolName: string, args: unknown): Record<string, unknown> {\n const normalized = isRecord(args) ? { ...args } : {}\n if (!(toolName in PUBLIC_MCP_TOOL_REQUIRED_ARGS)) return normalized\n\n const allowedArgs = PUBLIC_MCP_TOOL_ALLOWED_ARGS[toolName]\n if (!allowedArgs) return normalized\n return Object.fromEntries(Object.entries(normalized).filter(([key]) => allowedArgs.includes(key)))\n}\n\nfunction validateKnownPublicToolArguments(\n toolName: string,\n args: Record<string, unknown>\n): string | null {\n const requiredArgs = PUBLIC_MCP_TOOL_REQUIRED_ARGS[toolName]\n if (!requiredArgs) return null\n\n for (const argName of requiredArgs) {\n if (isBlankArgument(args[argName])) {\n return `Missing required argument: ${argName}`\n }\n }\n\n return null\n}\n\nfunction claudeFacingToolDescription(tool: McpTool): string {\n const baseDescription = KNOWN_PUBLIC_TOOL_DESCRIPTIONS[tool.name] ?? tool.description ?? tool.name\n const requiredArgs = PUBLIC_MCP_TOOL_REQUIRED_ARGS[tool.name]\n if (!requiredArgs) return baseDescription\n return [\n baseDescription,\n '',\n `Required arguments: ${requiredArgs.join(', ')}.`,\n 'If the user did not provide the network, ask for it before calling this tool. Do not guess a default network.',\n ].join('\\n')\n}\n\nfunction knownPublicToolAnnotations(toolName: string): Record<string, boolean> | undefined {\n if (\n toolName === 'graph_query' ||\n toolName === 'graph_query_batch' ||\n toolName.startsWith('aml_')\n ) {\n return {\n readOnlyHint: true,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: true,\n }\n }\n return undefined\n}\n\ntype RemoteToolResult = {\n content?: ContentBlock[]\n structuredContent?: Record<string, unknown>\n _meta?: Record<string, unknown>\n isError?: boolean\n}\n\nfunction promptResult(text: string, description?: string): GetPromptResult {\n return {\n description,\n messages: [\n {\n role: 'user',\n content: {\n type: 'text',\n text,\n },\n },\n ],\n }\n}\n\nfunction registerLocalPrompts(server: McpServer): void {\n server.registerPrompt(\n 'aml-address-risk',\n {\n title: 'AML Address Risk',\n description:\n 'Screen a blockchain address for AML risk, behavioral patterns, neighborhood profile, member addresses, and exchange links.',\n argsSchema: {\n network: NETWORK_SCHEMA,\n address: z.string().describe('Blockchain address to screen'),\n compare_address: z\n .string()\n .optional()\n .describe('Optional address to compare against the screened address'),\n },\n },\n async ({ network, address, compare_address }) =>\n promptResult(\n [\n `Use Chain Insights aml_address_risk on ${network} for:`,\n '',\n `\\`${address}\\``,\n compare_address ? `\\nCompare with: \\`${compare_address}\\`` : '',\n '',\n 'Present the summary as-is. Do not add analysis, verdicts, or risk assessments; the tool output already contains the risk assessment.',\n ]\n .filter(Boolean)\n .join('\\n'),\n 'AML address risk screening'\n )\n )\n\n server.registerPrompt(\n 'meta-network-capabilities',\n {\n title: 'Network Capabilities',\n description: 'Inspect supported networks and available tools before selecting a network.',\n argsSchema: {},\n },\n async () =>\n promptResult(\n 'Use Chain Insights meta_network_capabilities. Report only the supported networks and available tools exactly as returned; do not infer unsupported networks.',\n 'Network capabilities'\n )\n )\n\n server.registerPrompt(\n 'meta-usage-status',\n {\n title: 'Usage Status',\n description: \"Check the caller's public free graph_query quota.\",\n argsSchema: {},\n },\n async () =>\n promptResult(\n 'Use Chain Insights meta_usage_status. Report the quota fields exactly as returned.',\n 'Usage status'\n )\n )\n\n server.registerPrompt(\n 'graph-query',\n {\n title: 'Graph Query',\n description: 'Run a read-only GQL/Cypher query through the Chain Insights graph endpoint.',\n argsSchema: {\n network: NETWORK_SCHEMA,\n query: z.string().describe('Read-only GQL/Cypher query'),\n },\n },\n async ({ network, query }) =>\n promptResult(\n [\n `Use Chain Insights graph_query on ${network} with this read-only GQL/Cypher query:`,\n '',\n '```gql',\n query,\n '```',\n '',\n 'Use USE topology for topology (address/FLOWS_TO/LINKED graph, unified recent+historical, plus the node risk_score/risk_level verdict) and USE facts for bounded TRANSFER rows and enrichment. If you need schema context, first run small discovery queries such as MATCH (a:Address) RETURN a.address AS address, keys(a) AS address_properties LIMIT 5 and MATCH (:Address)-[r:FLOWS_TO]->(:Address) RETURN keys(r) AS flow_properties LIMIT 5. Return the full address when available; never shorten addresses with ellipses.',\n ].join('\\n'),\n 'Graph query'\n )\n )\n\n server.registerPrompt(\n 'graph-query-batch',\n {\n title: 'Graph Query Batch',\n description:\n 'Run related read-only GQL/Cypher queries through the Chain Insights graph endpoint in one paid batch.',\n argsSchema: {\n network: NETWORK_SCHEMA,\n queries: z\n .string()\n .describe('JSON array of query objects with optional id and required query fields'),\n per_query_timeout_seconds: z\n .string()\n .optional()\n .describe('Optional integer timeout per query, 1-600 seconds'),\n },\n },\n async ({ network, queries, per_query_timeout_seconds }) =>\n promptResult(\n [\n `Use Chain Insights graph_query_batch on ${network} with these read-only GQL/Cypher queries:`,\n '',\n '```json',\n queries,\n '```',\n per_query_timeout_seconds\n ? `per_query_timeout_seconds: ${per_query_timeout_seconds}`\n : '',\n '',\n 'Use USE topology for topology (address/FLOWS_TO/LINKED graph, unified recent+historical, plus the node risk_score/risk_level verdict) and USE facts for bounded TRANSFER rows and enrichment. If you need schema context, first run small discovery queries such as MATCH (a:Address) RETURN a.address AS address, keys(a) AS address_properties LIMIT 5 and MATCH (:Address)-[r:FLOWS_TO]->(:Address) RETURN keys(r) AS flow_properties LIMIT 5. Return the full address when available; never shorten addresses with ellipses.',\n ]\n .filter(Boolean)\n .join('\\n'),\n 'Graph query batch'\n )\n )\n\n server.registerPrompt(\n 'wallet-balance',\n {\n title: 'Wallet Balance',\n description:\n 'Show the local Chain Insights payment wallet address, payment network, token, and amount.',\n argsSchema: {},\n },\n async () =>\n promptResult(\n 'Use Chain Insights wallet_balance. Show the wallet address, payment network, token, and amount exactly as returned.',\n 'Wallet balance'\n )\n )\n\n server.registerPrompt(\n 'meta-help',\n {\n title: 'Chain Insights Help',\n description: 'Show available Chain Insights tools and workspace workflow.',\n argsSchema: {},\n },\n async () =>\n promptResult(\n 'Use Chain Insights meta_help. Summarize the available tools and workspace workflow without inventing capabilities.',\n 'Chain Insights help'\n )\n )\n}\n\nfunction hasGraphArrayFields(value: unknown): boolean {\n if (!value || typeof value !== 'object' || Array.isArray(value)) return false\n const record = value as Record<string, unknown>\n return GRAPH_ARRAY_KEYS.some((key) => Array.isArray(record[key]))\n}\n\nfunction sanitizeStructuredContentForGraphPayload(\n structuredContent: Record<string, unknown> | undefined\n): Record<string, unknown> | undefined {\n if (!structuredContent) return undefined\n return sanitizeStructuredValue(structuredContent) as Record<string, unknown>\n}\n\nfunction sanitizeStructuredValue(value: unknown): unknown {\n if (!value || typeof value !== 'object' || Array.isArray(value)) return value\n\n const sanitized: Record<string, unknown> = {}\n for (const [key, childValue] of Object.entries(value)) {\n if (key === 'app_data') continue\n if (\n GRAPH_ARRAY_KEYS.includes(key as (typeof GRAPH_ARRAY_KEYS)[number]) &&\n Array.isArray(childValue)\n ) {\n continue\n }\n sanitized[key] = sanitizeStructuredValue(childValue)\n }\n\n return sanitized\n}\n\nfunction getRemoteGraphPayload(result: RemoteToolResult): Record<string, unknown> | null {\n const chainInsights = result._meta?.chainInsights\n if (!chainInsights || typeof chainInsights !== 'object' || Array.isArray(chainInsights))\n return null\n const graph = (chainInsights as Record<string, unknown>).graph\n if (graph === undefined) return null\n if (!graph || typeof graph !== 'object' || Array.isArray(graph)) {\n throw new Error('Invalid remote graph payload')\n }\n\n const graphRecord = graph as Record<string, unknown>\n if (!('data' in graphRecord)) {\n if ('url' in graphRecord || hasGraphArrayFields(graphRecord)) {\n throw new Error('Invalid remote graph payload')\n }\n return null\n }\n\n const data = graphRecord.data\n if (!data || typeof data !== 'object' || Array.isArray(data)) {\n throw new Error('Invalid remote graph payload')\n }\n\n return data as Record<string, unknown>\n}\n\nasync function normalizeRemoteToolResult(\n result: RemoteToolResult,\n config: Pick<InvestigatorConfig, 'dataDir' | 'serverPort'>,\n toolName = 'remote-graph',\n includeAttachments = true\n) {\n const graphPayload = getRemoteGraphPayload(result)\n const meta = { ...(result._meta ?? {}) }\n\n if (graphPayload && includeAttachments) {\n const { writeGraphReport } = await import('./graph-reports.js')\n const { ensureArtifactServer } = await import('./artifact-server.js')\n const report = await writeGraphReport(graphPayload as never, {\n serverPort: config.serverPort,\n slug: toolName || 'remote-graph',\n })\n await ensureArtifactServer(config.serverPort)\n meta.chainInsights = {\n ...((meta.chainInsights as Record<string, unknown>) ?? {}),\n graph: {\n schema: report.schema,\n url: report.url,\n },\n }\n }\n\n return {\n content: result.content ?? [],\n structuredContent: sanitizeStructuredContentForGraphPayload(result.structuredContent),\n _meta: Object.keys(meta).length > 0 ? meta : undefined,\n isError: result.isError,\n }\n}\n\nfunction shouldIncludeAttachments(\n args: Record<string, unknown>,\n workspaceArtifactsEnabled: boolean\n): boolean {\n return workspaceArtifactsEnabled && args['include_attachments'] !== false\n}\n\nasync function writeLocalGraphMeta(\n graphData: unknown,\n config: Pick<InvestigatorConfig, 'dataDir' | 'serverPort'>,\n slug: string,\n includeAttachments: boolean\n): Promise<ChainInsightsGraphMeta | undefined> {\n if (!includeAttachments) return undefined\n const { writeGraphReport } = await import('./graph-reports.js')\n const { ensureArtifactServer } = await import('./artifact-server.js')\n const report = await writeGraphReport(graphData as never, {\n serverPort: config.serverPort,\n slug,\n })\n await ensureArtifactServer(config.serverPort)\n return {\n schema: report.schema,\n url: report.url,\n }\n}\n\nfunction graphMetaResult(\n graph: ChainInsightsGraphMeta | undefined\n): Record<string, unknown> | undefined {\n return graph\n ? {\n chainInsights: {\n graph,\n },\n }\n : undefined\n}\n\nfunction cleanNetworkCapabilities(value: unknown) {\n const structuredContent = isRecord(value) ? value.structuredContent : undefined\n const facts = isRecord(structuredContent) ? structuredContent.facts : undefined\n const capabilities = isRecord(facts) ? facts.capabilities : undefined\n const networks =\n isRecord(capabilities) && Array.isArray(capabilities.networks) ? capabilities.networks : []\n\n return {\n schema: 'chain-insights.result.v1' as const,\n tool: 'meta_network_capabilities',\n hint: null,\n facts: {\n capabilities: mirrorGraphNetworkCapabilities({ networks }),\n },\n }\n}\n\nfunction jsonTextResult(structuredContent: Record<string, unknown>) {\n return {\n content: [{ type: 'text' as const, text: JSON.stringify(structuredContent, null, 2) }],\n structuredContent,\n isError: false,\n }\n}\n\n/**\n * Core proxy logic — exported so tests can inject dependencies directly.\n * The IIFE at the bottom calls this with real dependencies.\n *\n * stdout purity: NEVER write to stdout in this file. Use console.error() or process.stderr.write() only.\n * All diagnostic output goes to console.error() or process.stderr.write().\n */\nexport async function createProxy(): Promise<void> {\n // Lazy imports to avoid module-load side effects (critical for stdio proxy)\n const { loadConfig } = await import('../config/index.js')\n const { activeDataDir, findActiveWorkspace } = await import('../workspace/active.js')\n const { createConfiguredGraphMcpFetch, resolveGraphMcpEndpoint } = await import('./client.js')\n const { loadSchema, saveSchema } = await import('./schema-cache.js')\n\n const proxyMode = resolveMcpProxyMode()\n const workspaceArtifactsEnabled = proxyMode === 'workspace'\n const loadedConfig = await loadConfig()\n const activeWorkspace = workspaceArtifactsEnabled ? findActiveWorkspace() : null\n const config = {\n ...loadedConfig,\n dataDir: workspaceArtifactsEnabled ? activeDataDir(loadedConfig.dataDir) : loadedConfig.dataDir,\n }\n const logger = createMcpLogger(config)\n await logger.info('proxy.start', {\n data_dir: config.dataDir,\n workspace_root: activeWorkspace?.root,\n proxy_mode: proxyMode,\n graph_mcp_mode: config.graphMcpMode,\n graph_mcp_endpoint: resolveGraphMcpEndpoint(config),\n log_path: logger.filePath,\n })\n const graphMcpEndpoint = resolveGraphMcpEndpoint(config)\n\n // Build remote MCP client. The local Chain Insights MCP surface must still\n // start when the graph endpoint is temporarily unavailable so agents can use\n // help and wallet tools.\n const remoteClient = new Client({ name: 'chain-insights-proxy-client', version: PACKAGE_VERSION })\n let remoteConnected = false\n let remoteUnavailableMessage: string | undefined\n let mcpFetch: typeof fetch | undefined\n\n try {\n mcpFetch = await createConfiguredGraphMcpFetch(config)\n } catch (err) {\n await logger.error('remote.fetch_setup_failed', {\n endpoint: graphMcpEndpoint,\n error: errorForLog(err),\n })\n remoteUnavailableMessage = `Chain Insights Graph setup unavailable at ${graphMcpEndpoint}: ${(err as Error).message}`\n process.stderr.write(\n `Chain Insights MCP graph tools unavailable: ${remoteUnavailableMessage}. Local Chain Insights tools are still available.\\n`\n )\n }\n\n if (mcpFetch) {\n try {\n await remoteClient.connect(\n new StreamableHTTPClientTransport(new URL(graphMcpEndpoint), { fetch: mcpFetch })\n )\n remoteConnected = true\n await logger.info('remote.connect', {\n transport: 'streamable_http',\n endpoint: graphMcpEndpoint,\n })\n } catch {\n await logger.error('remote.connect_failed', {\n transport: 'streamable_http',\n endpoint: graphMcpEndpoint,\n })\n // StreamableHTTP failed — try SSE fallback (assumption A1 from RESEARCH.md)\n try {\n const { SSEClientTransport } = await import('@modelcontextprotocol/sdk/client/sse.js')\n await remoteClient.connect(\n new SSEClientTransport(new URL(graphMcpEndpoint), { fetch: mcpFetch })\n )\n remoteConnected = true\n await logger.info('remote.connect', {\n transport: 'sse',\n endpoint: graphMcpEndpoint,\n })\n } catch (err2) {\n await logger.error('remote.connect_failed', {\n transport: 'sse',\n endpoint: graphMcpEndpoint,\n error: errorForLog(err2),\n })\n remoteUnavailableMessage = `Chain Insights Graph unreachable at ${graphMcpEndpoint}: ${(err2 as Error).message}`\n process.stderr.write(\n `Chain Insights MCP graph tools unavailable: ${remoteUnavailableMessage}. Local Chain Insights tools are still available.\\n`\n )\n }\n }\n }\n if (remoteConnected)\n installRemoteCypherLogging(remoteClient as unknown as RemoteToolCaller, logger)\n\n // Schema cache check — skip remote listTools call on cache hit\n let tools: McpTool[] | null = await loadSchema(graphMcpEndpoint)\n\n if (!tools && remoteConnected) {\n // Cache miss — fetch tools from remote (client is already connected above)\n const result = await remoteClient.listTools()\n tools = result.tools as McpTool[]\n await saveSchema(tools, graphMcpEndpoint)\n await logger.info('schema.tools_loaded', {\n source: 'remote',\n count: tools.length,\n })\n } else if (tools) {\n await logger.info('schema.tools_loaded', {\n source: 'cache',\n count: tools.length,\n })\n } else {\n tools = fallbackGraphPrimitiveTools()\n await logger.info('schema.tools_loaded', {\n source: 'unavailable',\n count: tools.length,\n })\n }\n const remoteToolNames = new Set((tools ?? []).map((tool) => tool.name))\n\n // Build local stdio proxy server\n const server = new McpServer(\n { name: 'chain-insights', version: PACKAGE_VERSION },\n {\n instructions: workspaceArtifactsEnabled ? SERVER_INSTRUCTIONS : STATELESS_SERVER_INSTRUCTIONS,\n }\n )\n installToolLogging(server, logger)\n\n if (remoteConnected) {\n try {\n await remoteClient.listPrompts()\n } catch (err) {\n await logger.error('remote.prompts_failed', {\n endpoint: graphMcpEndpoint,\n error: errorForLog(err),\n })\n process.stderr.write(\n `Chain Insights MCP remote prompt metadata unavailable at ${graphMcpEndpoint}: ${(err as Error).message}\\n`\n )\n }\n }\n\n registerLocalPrompts(server)\n\n const caseToolError = (label: string, err: unknown) => ({\n content: [{ type: 'text' as const, text: `${label} failed: ${(err as Error).message}` }],\n isError: true,\n })\n\n const parseTags = (tags: string | string[] | undefined): string[] => {\n if (Array.isArray(tags)) return tags.map((tag) => tag.trim()).filter(Boolean)\n if (typeof tags === 'string')\n return tags\n .split(',')\n .map((tag) => tag.trim())\n .filter(Boolean)\n return []\n }\n\n server.registerTool(\n 'meta_network_capabilities',\n {\n title: 'Network Capabilities',\n description: KNOWN_PUBLIC_TOOL_DESCRIPTIONS.meta_network_capabilities,\n inputSchema: EMPTY_INPUT_SCHEMA,\n annotations: {\n readOnlyHint: true,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n },\n },\n async () => {\n if (remoteConnected && remoteToolNames.has('network_capabilities')) {\n try {\n const result = await remoteClient.callTool({\n name: 'network_capabilities',\n arguments: {},\n })\n return jsonTextResult(cleanNetworkCapabilities(result))\n } catch (err) {\n return {\n content: [\n {\n type: 'text' as const,\n text: `Network capabilities failed: ${(err as Error).message}`,\n },\n ],\n isError: true,\n }\n }\n }\n return jsonTextResult(cleanNetworkCapabilities(undefined))\n }\n )\n\n server.registerTool(\n 'meta_usage_status',\n {\n title: 'Usage Status',\n description: KNOWN_PUBLIC_TOOL_DESCRIPTIONS.meta_usage_status,\n inputSchema: EMPTY_INPUT_SCHEMA,\n annotations: {\n readOnlyHint: true,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: true,\n },\n },\n async () => {\n try {\n if (!remoteConnected) {\n return {\n content: [\n {\n type: 'text' as const,\n text: `${remoteUnavailableMessage ?? `Chain Insights Graph is not connected at ${graphMcpEndpoint}`}. Restart the Chain Insights MCP proxy after the endpoint is reachable.`,\n },\n ],\n isError: true,\n }\n }\n if (!remoteToolNames.has('usage_status')) {\n return jsonTextResult(primitiveBackendUsageStatus(graphMcpEndpoint))\n }\n const result = (await remoteClient.callTool({\n name: 'usage_status',\n arguments: {},\n })) as RemoteToolResult\n const structuredContent = isRecord(result.structuredContent)\n ? { ...result.structuredContent, tool: 'meta_usage_status' }\n : undefined\n return {\n content: structuredContent\n ? [{ type: 'text' as const, text: JSON.stringify(structuredContent, null, 2) }]\n : (result.content ?? []),\n structuredContent,\n _meta: result._meta,\n isError: result.isError,\n }\n } catch (err) {\n return {\n content: [\n { type: 'text' as const, text: `Usage status failed: ${(err as Error).message}` },\n ],\n isError: true,\n }\n }\n }\n )\n\n if (workspaceArtifactsEnabled) {\n server.registerTool(\n 'wallet_balance',\n {\n title: 'Wallet Balance',\n description: KNOWN_PUBLIC_TOOL_DESCRIPTIONS.wallet_balance,\n inputSchema: EMPTY_INPUT_SCHEMA,\n annotations: {\n readOnlyHint: true,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: true,\n },\n },\n async () => {\n try {\n const { formatWalletBalanceResult, getWalletAccount, getWalletBalanceResult } =\n await import('../wallet/tools.js')\n const account = await getWalletAccount()\n const structuredContent = await getWalletBalanceResult(account)\n return {\n content: [\n { type: 'text' as const, text: formatWalletBalanceResult(structuredContent) },\n ],\n structuredContent: structuredContent as unknown as Record<string, unknown>,\n isError: false,\n }\n } catch (err) {\n return {\n content: [{ type: 'text' as const, text: `Balance failed: ${(err as Error).message}` }],\n isError: true,\n }\n }\n }\n )\n }\n // NOTE: only wallet_balance is workspace-only. Everything below — the graph\n // app resource, the aml_*/graph tools, and server.connect() — is shared and\n // MUST run in stateless mode too. (Regression #136: this brace had drifted to\n // the end of the function, so stateless mode skipped server.connect entirely.)\n\n registerAppResource(\n server,\n 'Fund Flow Graph',\n GRAPH_RESOURCE_URI,\n {\n description:\n 'Interactive fund-flow and pattern graph for Chain Insights investigation reports.',\n _meta: {\n ui: {\n csp: {\n resourceDomains: graphArtifactOrigins(config),\n connectDomains: graphArtifactOrigins(config),\n },\n },\n },\n },\n async () => ({\n contents: [\n {\n uri: GRAPH_RESOURCE_URI,\n mimeType: RESOURCE_MIME_TYPE,\n text: readGraphAppHtml(),\n _meta: {\n ui: {\n csp: {\n resourceDomains: graphArtifactOrigins(config),\n connectDomains: graphArtifactOrigins(config),\n },\n },\n },\n },\n ],\n })\n )\n\n if (!remoteToolNames.has('aml_address_risk')) {\n registerAppTool(\n server,\n 'aml_address_risk',\n {\n title: 'Address Risk',\n description: KNOWN_PUBLIC_TOOL_DESCRIPTIONS.aml_address_risk,\n inputSchema: {\n address: z.string().min(1).describe('Blockchain address to screen'),\n network: NETWORK_SCHEMA,\n compare_address: z\n .string()\n .optional()\n .describe('Optional address to compare against the screened address'),\n include_attachments: z.boolean().optional().describe('Include graph app report metadata'),\n },\n _meta: {\n ui: {\n resourceUri: GRAPH_RESOURCE_URI,\n },\n },\n annotations: {\n readOnlyHint: true,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: true,\n },\n },\n async ({ address, network, compare_address, include_attachments }) => {\n try {\n if (!remoteConnected) {\n return {\n content: [\n {\n type: 'text' as const,\n text: `${remoteUnavailableMessage ?? `Chain Insights Graph is not connected at ${graphMcpEndpoint}`}. Restart the Chain Insights MCP proxy after the endpoint is reachable.`,\n },\n ],\n isError: true,\n }\n }\n const { addressRisk } = await import('../investigation/public-tools.js')\n const result = await addressRisk(remoteClient, {\n address,\n network,\n compareAddress: compare_address,\n writeArtifacts: workspaceArtifactsEnabled,\n })\n const graph = await writeLocalGraphMeta(\n result.graphData,\n config,\n `address-risk-${network}-${address}`,\n shouldIncludeAttachments({ include_attachments }, workspaceArtifactsEnabled)\n )\n return {\n content: [{ type: 'text' as const, text: result.summaryText }],\n structuredContent: result.structuredContent,\n _meta: graphMetaResult(graph),\n isError: false,\n }\n } catch (err) {\n if (err instanceof PaymentRequiredError) {\n return { content: [{ type: 'text' as const, text: err.message }], isError: true }\n }\n return {\n content: [\n { type: 'text' as const, text: `Address risk failed: ${(err as Error).message}` },\n ],\n isError: true,\n }\n }\n }\n )\n }\n\n server.registerTool(\n 'meta_help',\n {\n title: 'Chain Insights Help',\n description: KNOWN_PUBLIC_TOOL_DESCRIPTIONS.meta_help,\n inputSchema: EMPTY_INPUT_SCHEMA,\n annotations: {\n readOnlyHint: true,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n },\n },\n async () => ({\n content: [\n {\n type: 'text' as const,\n text: workspaceArtifactsEnabled\n ? [\n 'Chain Insights helps AI agents run AML investigation workflows and keep evidence in local workspace files.',\n '',\n CHAIN_INSIGHTS_WORKFLOW,\n '',\n 'Investigation tools:',\n '- meta_network_capabilities: inspect supported networks and available tools.',\n '- meta_usage_status: check the caller public free graph_query quota.',\n '- aml_address_risk: screen one blockchain address; optionally compare it with another address.',\n '- graph_query: run read-only GQL/Cypher through the universal graph endpoint. Use USE topology or USE facts.',\n '- graph_query_batch: run related read-only graph-language queries through one paid graph call.',\n '',\n 'Wallet tools:',\n '- wallet_balance: show the local payment wallet address, payment network, token, and amount.',\n '- meta_help: show this overview.',\n '',\n GRAPH_REPORT_HINTS,\n ].join('\\n')\n : [\n 'Chain Insights stateless AML proxy for host applications.',\n '',\n 'Local workspace persistence, wallet, and graph report attachment tools are disabled in this mode.',\n '',\n 'Available graph-backed tools:',\n '- meta_network_capabilities: inspect supported networks and available tools.',\n '- meta_usage_status: check the caller public free graph_query quota.',\n '- aml_address_risk: screen one blockchain address; optionally compare it with another address.',\n '- graph_query: run read-only GQL/Cypher through the universal graph endpoint. Use USE topology or USE facts.',\n '- graph_query_batch: run related read-only graph-language queries through one paid graph call.',\n ].join('\\n'),\n },\n ],\n isError: false,\n })\n )\n\n // Register each remote tool locally — passthrough proxy pattern\n for (const tool of tools ?? []) {\n if (HIDDEN_REMOTE_TOOL_NAMES.has(tool.name)) continue\n if (LOCAL_TOOL_NAMES.has(tool.name)) continue\n const inputSchema = knownPublicToolInputSchema(tool.name) ?? z.object({}).passthrough()\n const handler = async (args: unknown) => {\n try {\n if (!remoteConnected) {\n return {\n content: [\n {\n type: 'text' as const,\n text: `${remoteUnavailableMessage ?? `Chain Insights Graph is not connected at ${graphMcpEndpoint}`}. Restart the Chain Insights MCP proxy after the endpoint is reachable.`,\n },\n ],\n isError: true,\n }\n }\n const normalizedArgs = normalizeRemoteToolArguments(tool.name, args)\n const validationError = validateKnownPublicToolArguments(tool.name, normalizedArgs)\n if (validationError) {\n return {\n content: [{ type: 'text' as const, text: validationError }],\n isError: true,\n }\n }\n const request = {\n name: tool.name,\n arguments: normalizedArgs,\n }\n const requestOptions = remoteToolRequestOptions(tool.name)\n const result = requestOptions\n ? await remoteClient.callTool(request, undefined, requestOptions)\n : await remoteClient.callTool(request)\n return await normalizeRemoteToolResult(\n result as RemoteToolResult,\n config,\n tool.name,\n shouldIncludeAttachments(normalizedArgs, workspaceArtifactsEnabled)\n )\n } catch (err) {\n if (err instanceof PaymentRequiredError) {\n return {\n content: [{ type: 'text' as const, text: err.message }],\n isError: true,\n }\n }\n const msg = (err as Error).message ?? String(err)\n const isTransport402 = /\\b402\\b/.test(msg) || msg.toLowerCase().includes('payment')\n if (isTransport402) {\n return {\n content: [\n {\n type: 'text' as const,\n text:\n `Payment required for ${tool.name}. This tool costs USDC on Base via x402 micropayments. ` +\n 'Next steps: run `chain-insights wallet ready` to check funding and finish one-time payment setup, ' +\n 'run `chain-insights wallet topup` if it says the wallet needs USDC, ' +\n 'or `chain-insights access-key set <key>` if you have been given test access.',\n },\n ],\n isError: true,\n }\n }\n return {\n content: [{ type: 'text' as const, text: `MCP call failed: ${msg}` }],\n isError: true,\n }\n }\n }\n const toolConfig = {\n title: tool.title,\n description: claudeFacingToolDescription(tool),\n inputSchema,\n ...(knownPublicToolAnnotations(tool.name)\n ? { annotations: knownPublicToolAnnotations(tool.name) }\n : {}),\n }\n\n if (hasGraphApp(tool)) {\n registerAppTool(\n server,\n tool.name,\n {\n ...toolConfig,\n _meta: graphToolMeta(tool),\n },\n handler\n )\n } else {\n server.registerTool(tool.name, toolConfig, handler)\n }\n }\n\n // Connect to stdio transport — after this line, stdout belongs to MCP\n const transport = new StdioServerTransport()\n await server.connect(transport)\n await logger.info('proxy.ready', {\n tools: [\n ...LOCAL_TOOL_NAMES,\n ...(tools ?? [])\n .map((tool) => tool.name)\n .filter((name) => !HIDDEN_REMOTE_TOOL_NAMES.has(name) && !LOCAL_TOOL_NAMES.has(name)),\n ].length,\n })\n\n // Signal handling — clean shutdown\n const shutdown = async () => {\n await logger.info('proxy.shutdown')\n transport.close()\n process.exit(0)\n }\n process.on('SIGINT', () => {\n void shutdown()\n })\n process.on('SIGTERM', () => {\n void shutdown()\n })\n}\n\n// Entry point — only execute when run as the main module (not when imported by tests)\n// Using process.argv check to detect direct execution vs import\nif (process.argv[1] && import.meta.url.includes(process.argv[1].replace(/\\\\/g, '/'))) {\n createProxy().catch((err) => {\n process.stderr.write(`Chain Insights MCP proxy startup failed: ${(err as Error).message}\\n`)\n process.exit(1)\n })\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AA4BA,MAAM,mCAAmB,IAAI,IAAI;CAC/B;CACA;CACA;CACA;AACF,CAAC;AACD,MAAM,qBAAqB;AAC3B,MAAM,uCAAuB,IAAI,IAAI,CAAC,kBAAkB,CAAC;AACzD,MAAM,mBAAmB;CAAC;CAAS;CAAS;CAAS;AAAc;AACnE,MAAM,YAAY,KAAK,QAAQ,cAAc,YAAY,GAAG,CAAC;AAI7D,SAAgB,oBAAoB,MAAyB,QAAQ,KAAmB;CACtF,MAAM,MAAM,IAAI,gCAAgC,EAAE,KAAK,CAAC,CAAC,YAAY;CACrE,IAAI,CAAC,OAAO,QAAQ,aAAa,OAAO;CACxC,IAAI,QAAQ,eAAe,QAAQ,kBAAkB,QAAQ,kBAAkB,OAAO;CACtF,MAAM,IAAI,M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AAIA,IAAI,QAAQ,KAAK,MAAM,YAAY,IAAI,SAAS,QAAQ,KAAK,EAAE,CAAC,QAAQ,OAAO,GAAG,CAAC,GACjF,YAAY,CAAC,CAAC,OAAO,QAAQ;CAC3B,QAAQ,OAAO,MAAM,4CAA6C,IAAc,QAAQ,GAAG;CAC3F,QAAQ,KAAK,CAAC;AAChB,CAAC"}
@@ -34,7 +34,7 @@ function rowKey(row) {
34
34
  * shard's raw values directly.
35
35
  *
36
36
  * Per-property rules (SPEC-2026-07-26-FED-THIN-FANOUT, mirrored from the
37
- * retired server-side merge in data-pipeline internal/graphmcp/federation.go
37
+ * retired server-side merge in the retired internal federation merger
38
38
  * which solved the same problem before the merge moved client-side):
39
39
  *
40
40
  * - `amount_usd_sum`, `tx_count`: additive per-shard partials — summed.
@@ -196,4 +196,4 @@ function mergeShardRows(rows, opts = {}) {
196
196
  //#endregion
197
197
  export { mergeShardRows as t };
198
198
 
199
- //# sourceMappingURL=merge-CJRZpuZ4.mjs.map
199
+ //# sourceMappingURL=merge-BZw-pMPN.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"merge-BZw-pMPN.mjs","names":[],"sources":["../src/federation/merge.ts"],"sourcesContent":["/**\n * Client-side merge for federated topology results.\n *\n * graphrag-mcp pushes the caller's query verbatim to every covering shard and\n * returns the rows tagged with `__shard`, merging nothing (SPEC-2026-07-26-\n * FED-THIN-FANOUT). Merge semantics are a client concern: whether \"hub\" means\n * max-over-shards or sum-over-shards is a detection decision the server cannot\n * make. This module is the reference implementation.\n *\n * Pure: no network, no config, no mutation of the caller's rows.\n */\n\nexport type ShardRow = Record<string, unknown> & { __shard?: string }\n\nexport interface MergeOptions {\n orderBy?: { key: string; desc?: boolean }\n limit?: number\n edgeKey?: (edge: Record<string, unknown>) => string | null\n /** Columns the caller asserts are non-mergeable aggregates. They are lifted\n * out of the rows into `perShard` so no consumer can sum them by accident\n * (SPEC A7). The merge cannot infer these — naming them is the assertion.\n * A shard may return more than one row for the same aggregate column when\n * the query groups by another column (e.g. `RETURN counterparty,\n * sum(...) AS usd`) — `perShard[shard]` holds one entry per such row, so\n * two differently-grouped rows from the same shard can never collide. */\n aggregateKeys?: string[]\n /** Whether the sort key survives merging. `invariant` keys (address, labels)\n * give an exact global order; `merge-affected` keys (sums) do not, because a\n * pair ranked 4th in every shard can be 1st once merged (SPEC D3). */\n orderKeyClass?: 'invariant' | 'merge-affected'\n}\n\nexport interface MergedResult {\n rows: Array<Record<string, unknown>>\n /** One entry per aggregate row a shard returned (see `aggregateKeys`),\n * carrying that row's grouping columns alongside its aggregate columns.\n * An array, not a shard-keyed object, so a second group from the same\n * shard is appended rather than overwriting the first. */\n perShard: Record<string, Array<Record<string, unknown>>>\n ordering: 'exact' | 'approximate' | 'unordered'\n}\n\nconst SHARD_KEY = '__shard'\n\nfunction numeric(value: unknown): number | null {\n return typeof value === 'number' && Number.isFinite(value) ? value : null\n}\n\nfunction isEdgeObject(\n value: unknown\n): value is { type: string; properties: Record<string, unknown> } {\n if (typeof value !== 'object' || value === null) return false\n const candidate = value as Record<string, unknown>\n return (\n typeof candidate.type === 'string' &&\n typeof candidate.properties === 'object' &&\n candidate.properties !== null\n )\n}\n\n/** Identity of a row for dedup/merge purposes. Edge rows key on the edge's\n * endpoints; plain rows key on their non-shard content. */\nfunction rowKey(row: ShardRow): string {\n const parts: string[] = []\n for (const [key, value] of Object.entries(row)) {\n if (key === SHARD_KEY) continue\n if (isEdgeObject(value)) {\n const props = value.properties\n parts.push(`${key} edge ${String(props.from_address)} ${String(props.to_address)}`)\n continue\n }\n parts.push(`${key} ${JSON.stringify(value)}`)\n }\n return parts.join('')\n}\n\n/**\n * Combines every shard's contribution to the SAME logical edge (same\n * from_address/to_address, the identity `rowKey` groups on) into one\n * lifetime edge. `constituents` is every contributing shard's `.properties`\n * object, in first-seen order.\n *\n * This is a single N-way fold over all constituents at once, not a pairwise\n * fold of an accumulator, so every per-property rule below reads each\n * shard's raw values directly.\n *\n * Per-property rules (SPEC-2026-07-26-FED-THIN-FANOUT, mirrored from the\n * retired server-side merge in the retired internal federation merger\n * which solved the same problem before the merge moved client-side):\n *\n * - `amount_usd_sum`, `tx_count`: additive per-shard partials — summed.\n * - `first_seen_timestamp`: MIN across shards. `first_tx_id` is NOT\n * shard-invariant — it identifies the transaction AT first_seen_timestamp\n * — so it must come from the SAME constituent that produced the min, not\n * whichever shard happened to merge first.\n * - `last_seen_timestamp`: MAX across shards, with `last_tx_id` from the\n * constituent that produced the max (mirror of `first_tx_id`).\n * - `avg_tx_size_usd`: an average is not carryable across shards — it is\n * recomputed from the merged totals (`amount_usd_sum / tx_count`, guarded\n * against division by zero) so it stays consistent with the summed totals\n * instead of leaking one shard's partial average.\n * - `price_coverage_ratio`: a tx-count-weighted mean,\n * Σ(ratio·tx_count)/Σtx_count. The ratio's own denominator IS tx_count\n * (priced tx / total tx), so weighting by tx_count and dividing by the\n * summed tx_count reconstructs the exact lifetime ratio rather than\n * averaging shard ratios naively (which would over-weight a low-volume\n * shard's ratio as much as a high-volume one).\n * - `dominant_asset` / `asset_usd_totals`: retired from the FLOWS_TO edge\n * contract (operator ruling 2026-07-28) — address-level asset features are\n * computed on demand, not carried as edge payload, so there is no merge\n * rule. A stale shard still returning them falls through to the\n * first-seen-wins fallback below.\n * - `bucket_start_timestamp` / `bucket_end_timestamp`: each describes ONE shard's own\n * coverage window. The merged edge's window is the outer span of every\n * contributing shard's window: `[MIN start, MAX end]`.\n * - `from_address`, `to_address`, `from_address_lookalike`,\n * `to_address_lookalike`: identity — `rowKey` already grouped these\n * constituents by from_address+to_address, so these are equal on every\n * constituent by construction (address-derived lookalike flags do not\n * vary per shard). The first-seen value carries through untouched.\n * - Any other property is outside the frozen FLOWS_TO contract this module\n * knows about; it keeps the first-seen constituent's value (unchanged\n * \"first non-null wins\" fallback).\n */\nfunction combineEdge(constituents: Array<Record<string, unknown>>): Record<string, unknown> {\n const out: Record<string, unknown> = {}\n // First-non-null-wins baseline for identity fields and any unlisted\n // property. Every property below this point is then explicitly\n // recomputed/overridden with its correct merge rule.\n for (const props of constituents) {\n for (const [key, value] of Object.entries(props)) {\n if (out[key] === undefined || out[key] === null) out[key] = value\n }\n }\n\n let amountSum = 0\n let txSum = 0\n let minFirst: number | null = null\n let firstTxId: unknown\n let maxLast: number | null = null\n let lastTxId: unknown\n let minBucketStart: number | null = null\n let maxBucketEnd: number | null = null\n let weightedRatioNum = 0\n let anyRatio = false\n\n for (const p of constituents) {\n const amount = numeric(p.amount_usd_sum) ?? 0\n const tx = numeric(p.tx_count) ?? 0\n amountSum += amount\n txSum += tx\n\n const first = numeric(p.first_seen_timestamp)\n if (first !== null && (minFirst === null || first < minFirst)) {\n minFirst = first\n firstTxId = p.first_tx_id\n }\n const last = numeric(p.last_seen_timestamp)\n if (last !== null && (maxLast === null || last > maxLast)) {\n maxLast = last\n lastTxId = p.last_tx_id\n }\n const bucketStart = numeric(p.bucket_start_timestamp)\n if (bucketStart !== null && (minBucketStart === null || bucketStart < minBucketStart)) {\n minBucketStart = bucketStart\n }\n const bucketEnd = numeric(p.bucket_end_timestamp)\n if (bucketEnd !== null && (maxBucketEnd === null || bucketEnd > maxBucketEnd)) {\n maxBucketEnd = bucketEnd\n }\n const ratio = numeric(p.price_coverage_ratio)\n if (ratio !== null) {\n weightedRatioNum += ratio * tx\n anyRatio = true\n }\n }\n\n out.amount_usd_sum = amountSum\n out.tx_count = txSum\n if (minFirst !== null) {\n out.first_seen_timestamp = minFirst\n if (firstTxId !== undefined) out.first_tx_id = firstTxId\n }\n if (maxLast !== null) {\n out.last_seen_timestamp = maxLast\n if (lastTxId !== undefined) out.last_tx_id = lastTxId\n }\n if (minBucketStart !== null) out.bucket_start_timestamp = minBucketStart\n if (maxBucketEnd !== null) out.bucket_end_timestamp = maxBucketEnd\n // Recomputed, never carried: an average from one shard is simply a wrong\n // number once other shards contribute.\n out.avg_tx_size_usd = txSum > 0 ? amountSum / txSum : 0\n if (anyRatio) out.price_coverage_ratio = txSum > 0 ? weightedRatioNum / txSum : 0\n\n return out\n}\n\nexport function mergeShardRows(rows: ShardRow[], opts: MergeOptions = {}): MergedResult {\n const aggregateKeys = opts.aggregateKeys ?? []\n const perShard: Record<string, Array<Record<string, unknown>>> = {}\n const mergeable: ShardRow[] = []\n for (const row of rows) {\n const shard = typeof row[SHARD_KEY] === 'string' ? (row[SHARD_KEY] as string) : ''\n const remainder: ShardRow = {}\n const aggregateEntry: Record<string, unknown> = {}\n let liftedAny = false\n for (const [key, value] of Object.entries(row)) {\n if (aggregateKeys.includes(key)) {\n aggregateEntry[key] = value\n liftedAny = true\n continue\n }\n remainder[key] = value\n }\n if (liftedAny && shard !== '') {\n // The grouping columns are whatever non-aggregate, non-__shard keys\n // this row carries (e.g. a GROUP BY alias). Pushing a new entry per\n // row — rather than assigning into an object keyed by shard alone —\n // means a second group from the same shard can never overwrite the\n // first: the array can only grow, never lose a write.\n const groupCols: Record<string, unknown> = {}\n for (const [key, value] of Object.entries(remainder)) {\n if (key === SHARD_KEY) continue\n groupCols[key] = value\n }\n perShard[shard] = perShard[shard] ?? []\n perShard[shard].push({ ...groupCols, ...aggregateEntry })\n }\n const hasContent = Object.keys(remainder).some((k) => k !== SHARD_KEY)\n if (!liftedAny || hasContent) mergeable.push(remainder)\n }\n\n // Group mergeable rows by identity key, preserving first-seen order, so\n // combineEdge can fold ALL constituents for a key at once (see combineEdge\n // for the per-property rules).\n const groups = new Map<string, ShardRow[]>()\n for (const row of mergeable) {\n const key = rowKey(row)\n const list = groups.get(key)\n if (list) list.push(row)\n else groups.set(key, [row])\n }\n\n const byKey = new Map<string, Record<string, unknown>>()\n for (const [key, group] of groups) {\n // Deep copy so the caller's rows are never mutated.\n const copy = JSON.parse(JSON.stringify(group[0])) as Record<string, unknown>\n delete copy[SHARD_KEY]\n if (group.length > 1) {\n for (const field of Object.keys(copy)) {\n if (!isEdgeObject(copy[field])) continue\n const constituents = group\n .map((g) => g[field])\n .filter(isEdgeObject)\n .map((edge) => edge.properties)\n ;(copy[field] as { properties: Record<string, unknown> }).properties =\n combineEdge(constituents)\n }\n }\n byKey.set(key, copy)\n }\n\n let out = [...byKey.values()]\n if (opts.orderBy) {\n const { key, desc } = opts.orderBy\n out.sort((a, b) => {\n const av = a[key] as never\n const bv = b[key] as never\n if (av === bv) return 0\n return (av < bv ? -1 : 1) * (desc ? -1 : 1)\n })\n }\n if (typeof opts.limit === 'number' && opts.limit >= 0) out = out.slice(0, opts.limit)\n const ordering: MergedResult['ordering'] = !opts.orderBy\n ? 'unordered'\n : opts.orderKeyClass === 'merge-affected'\n ? 'approximate'\n : 'exact'\n return { rows: out, perShard, ordering }\n}\n"],"mappings":";AA0CA,MAAM,YAAY;AAElB,SAAS,QAAQ,OAA+B;CAC9C,OAAO,OAAO,UAAU,YAAY,OAAO,SAAS,KAAK,IAAI,QAAQ;AACvE;AAEA,SAAS,aACP,OACgE;CAChE,IAAI,OAAO,UAAU,YAAY,UAAU,MAAM,OAAO;CACxD,MAAM,YAAY;CAClB,OACE,OAAO,UAAU,SAAS,YAC1B,OAAO,UAAU,eAAe,YAChC,UAAU,eAAe;AAE7B;;;AAIA,SAAS,OAAO,KAAuB;CACrC,MAAM,QAAkB,CAAC;CACzB,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,GAAG,GAAG;EAC9C,IAAI,QAAQ,WAAW;EACvB,IAAI,aAAa,KAAK,GAAG;GACvB,MAAM,QAAQ,MAAM;GACpB,MAAM,KAAK,GAAG,IAAI,QAAQ,OAAO,MAAM,YAAY,EAAE,GAAG,OAAO,MAAM,UAAU,GAAG;GAClF;EACF;EACA,MAAM,KAAK,GAAG,IAAI,GAAG,KAAK,UAAU,KAAK,GAAG;CAC9C;CACA,OAAO,MAAM,KAAK,EAAE;AACtB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkDA,SAAS,YAAY,cAAuE;CAC1F,MAAM,MAA+B,CAAC;CAItC,KAAK,MAAM,SAAS,cAClB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K,GAAG;OAClB,OAAO,IAAI,KAAK,CAAC,GAAG,CAAC;CAC5B;CAEA,MAAM,wBAAQ,IAAI,IAAqC;CACvD,KAAK,MAAM,CAAC,KAAK,UAAU,QAAQ;EAEjC,MAAM,OAAO,KAAK,MAAM,KAAK,UAAU,MAAM,EAAE,CAAC;EAChD,OAAO,KAAK;EACZ,IAAI,MAAM,SAAS,GACjB,KAAK,MAAM,SAAS,OAAO,KAAK,IAAI,GAAG;GACrC,IAAI,CAAC,aAAa,KAAK,MAAM,GAAG;GAChC,MAAM,eAAe,MAClB,KAAK,MAAM,EAAE,MAAM,CAAC,CACpB,OAAO,YAAY,CAAC,CACpB,KAAK,SAAS,KAAK,UAAU;GAC/B,KAAM,MAAM,CAA6C,aACxD,YAAY,YAAY;EAC5B;EAEF,MAAM,IAAI,KAAK,IAAI;CACrB;CAEA,IAAI,MAAM,CAAC,GAAG,MAAM,OAAO,CAAC;CAC5B,IAAI,KAAK,SAAS;EAChB,MAAM,EAAE,KAAK,SAAS,KAAK;EAC3B,IAAI,MAAM,GAAG,MAAM;GACjB,MAAM,KAAK,EAAE;GACb,MAAM,KAAK,EAAE;GACb,IAAI,OAAO,IAAI,OAAO;GACtB,QAAQ,KAAK,KAAK,KAAK,MAAM,OAAO,KAAK;EAC3C,CAAC;CACH;CACA,IAAI,OAAO,KAAK,UAAU,YAAY,KAAK,SAAS,GAAG,MAAM,IAAI,MAAM,GAAG,KAAK,KAAK;CACpF,MAAM,WAAqC,CAAC,KAAK,UAC7C,cACA,KAAK,kBAAkB,mBACrB,gBACA;CACN,OAAO;EAAE,MAAM;EAAK;EAAU;CAAS;AACzC"}
@@ -34,7 +34,7 @@ function rowKey(row) {
34
34
  * shard's raw values directly.
35
35
  *
36
36
  * Per-property rules (SPEC-2026-07-26-FED-THIN-FANOUT, mirrored from the
37
- * retired server-side merge in data-pipeline internal/graphmcp/federation.go
37
+ * retired server-side merge in the retired internal federation merger
38
38
  * which solved the same problem before the merge moved client-side):
39
39
  *
40
40
  * - `amount_usd_sum`, `tx_count`: additive per-shard partials — summed.
@@ -1,5 +1,5 @@
1
- const require_rolldown_runtime = require("./rolldown-runtime-DakpK96I.cjs");
2
- const require_active = require("./active-Bj6dohpc.cjs");
1
+ const require_rolldown_runtime = require("./rolldown-runtime-C0BPl7ul.cjs");
2
+ const require_active = require("./active-Bc13hJIm.cjs");
3
3
  let node_path = require("node:path");
4
4
  node_path = require_rolldown_runtime.__toESM(node_path, 1);
5
5
  //#region src/workspace/output-root.ts
@@ -1,6 +1,6 @@
1
- const require_rolldown_runtime = require("./rolldown-runtime-DakpK96I.cjs");
2
- const require_output_root = require("./output-root-C1PFNCqb.cjs");
3
- const require_merge = require("./merge-B_5kxbGv.cjs");
1
+ const require_rolldown_runtime = require("./rolldown-runtime-C0BPl7ul.cjs");
2
+ const require_output_root = require("./output-root-BewoQaTx.cjs");
3
+ const require_merge = require("./merge-C52eaAGU.cjs");
4
4
  const require_graph_normalizer = require("./graph-normalizer-B2Q2lgVy.cjs");
5
5
  let node_path = require("node:path");
6
6
  node_path = require_rolldown_runtime.__toESM(node_path, 1);
@@ -135,8 +135,9 @@ function mergeGraphRows(rows, query) {
135
135
  ordering: "unordered",
136
136
  merged: false
137
137
  };
138
+ const options = deriveMergeOptionsFromQuery(query);
138
139
  return {
139
- ...require_merge.mergeShardRows(rows, deriveMergeOptionsFromQuery(query)),
140
+ ...require_merge.mergeShardRows(rows, options),
140
141
  merged: true
141
142
  };
142
143
  }
@@ -300,7 +301,7 @@ function wrapClientForUsageTracking(client, totals) {
300
301
  //#endregion
301
302
  //#region src/investigation/public-tools.ts
302
303
  const GRAPH_QUERY_BATCH_TIMEOUT_SECONDS = 10;
303
- const GRAPH_QUERY_BATCH_REQUEST_TIMEOUT_MS = 300 * 1e3;
304
+ const GRAPH_QUERY_BATCH_REQUEST_TIMEOUT_MS = 3e5;
304
305
  function escapeCypherString(value) {
305
306
  return value.replaceAll("\\", "\\\\").replaceAll("\"", "\\\"");
306
307
  }
@@ -708,7 +709,7 @@ function exchangeExposureFallbackScore(exchangeRows) {
708
709
  weightedUsd += shared ? usd * FALLBACK_SHARED_DAMPING : usd;
709
710
  }
710
711
  const factor = Math.log10(1 + Math.min(weightedUsd, FALLBACK_VALUE_SATURATION_USD)) / Math.log10(1000001);
711
- return Math.min(FALLBACK_MAX_SCORE, FALLBACK_BASE_SCORE + (FALLBACK_MAX_SCORE - FALLBACK_BASE_SCORE) * factor);
712
+ return Math.min(FALLBACK_MAX_SCORE, FALLBACK_BASE_SCORE + .5 * factor);
712
713
  }
713
714
  function riskAssessment(profile, labelRows, exchangeRows) {
714
715
  const mlRiskScore = firstNumber(profile["live_risk_score"]);
@@ -1070,7 +1071,7 @@ async function writeAddressRiskArtifacts(network, address, compareAddress, graph
1070
1071
  const tableHtmlPath = node_path.default.join(paths.reportsRoot, `${slug}.table.html`);
1071
1072
  const reportPath = node_path.default.join(paths.reportsRoot, `${slug}.aml-address-report.md`);
1072
1073
  const graphHtmlPath = node_path.default.join(paths.reportsRoot, `${slug}.graph.html`);
1073
- const { generateInlineGraphHtml } = await Promise.resolve().then(() => require("./html-generator-Ui29DLSD.cjs")).then((n) => n.html_generator_exports);
1074
+ const { generateInlineGraphHtml } = await Promise.resolve().then(() => require("./html-generator-B9f_GIi2.cjs")).then((n) => n.html_generator_exports);
1074
1075
  const csv = [[
1075
1076
  "direction",
1076
1077
  "exchange_address",
@@ -1,5 +1,5 @@
1
1
  import { n as workspaceOutputPaths } from "./output-root-BK4pdjyz.mjs";
2
- import { t as mergeShardRows } from "./merge-CJRZpuZ4.mjs";
2
+ import { t as mergeShardRows } from "./merge-BZw-pMPN.mjs";
3
3
  import { t as normalizeGraphPayload } from "./graph-normalizer-BA3Rbd6l.mjs";
4
4
  import path from "node:path";
5
5
  import { mkdir, writeFile } from "node:fs/promises";
@@ -133,8 +133,9 @@ function mergeGraphRows(rows, query) {
133
133
  ordering: "unordered",
134
134
  merged: false
135
135
  };
136
+ const options = deriveMergeOptionsFromQuery(query);
136
137
  return {
137
- ...mergeShardRows(rows, deriveMergeOptionsFromQuery(query)),
138
+ ...mergeShardRows(rows, options),
138
139
  merged: true
139
140
  };
140
141
  }
@@ -298,7 +299,7 @@ function wrapClientForUsageTracking(client, totals) {
298
299
  //#endregion
299
300
  //#region src/investigation/public-tools.ts
300
301
  const GRAPH_QUERY_BATCH_TIMEOUT_SECONDS = 10;
301
- const GRAPH_QUERY_BATCH_REQUEST_TIMEOUT_MS = 300 * 1e3;
302
+ const GRAPH_QUERY_BATCH_REQUEST_TIMEOUT_MS = 3e5;
302
303
  function escapeCypherString(value) {
303
304
  return value.replaceAll("\\", "\\\\").replaceAll("\"", "\\\"");
304
305
  }
@@ -706,7 +707,7 @@ function exchangeExposureFallbackScore(exchangeRows) {
706
707
  weightedUsd += shared ? usd * FALLBACK_SHARED_DAMPING : usd;
707
708
  }
708
709
  const factor = Math.log10(1 + Math.min(weightedUsd, FALLBACK_VALUE_SATURATION_USD)) / Math.log10(1000001);
709
- return Math.min(FALLBACK_MAX_SCORE, FALLBACK_BASE_SCORE + (FALLBACK_MAX_SCORE - FALLBACK_BASE_SCORE) * factor);
710
+ return Math.min(FALLBACK_MAX_SCORE, FALLBACK_BASE_SCORE + .5 * factor);
710
711
  }
711
712
  function riskAssessment(profile, labelRows, exchangeRows) {
712
713
  const mlRiskScore = firstNumber(profile["live_risk_score"]);
@@ -1068,7 +1069,7 @@ async function writeAddressRiskArtifacts(network, address, compareAddress, graph
1068
1069
  const tableHtmlPath = path.join(paths.reportsRoot, `${slug}.table.html`);
1069
1070
  const reportPath = path.join(paths.reportsRoot, `${slug}.aml-address-report.md`);
1070
1071
  const graphHtmlPath = path.join(paths.reportsRoot, `${slug}.graph.html`);
1071
- const { generateInlineGraphHtml } = await import("./html-generator-ClysZjfY.mjs").then((n) => n.n);
1072
+ const { generateInlineGraphHtml } = await import("./html-generator-D2BDzLED.mjs").then((n) => n.n);
1072
1073
  const csv = [[
1073
1074
  "direction",
1074
1075
  "exchange_address",
@@ -1151,4 +1152,4 @@ function htmlEscape(value) {
1151
1152
  //#endregion
1152
1153
  export { addressRisk };
1153
1154
 
1154
- //# sourceMappingURL=public-tools-B9_wXs2o.mjs.map
1155
+ //# sourceMappingURL=public-tools-BjqZGGAC.mjs.map