chain-insights 0.85.2 → 0.92.0

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 (89) hide show
  1. package/README.md +2 -0
  2. package/bin/install.cjs +2 -1
  3. package/dist/{active-q3yViZhc.cjs → active-COPA14FA.cjs} +2 -16
  4. package/dist/{active-D2aabYRF.mjs → active-CyC4jFka.mjs} +2 -7
  5. package/dist/{active-D2aabYRF.mjs.map → active-CyC4jFka.mjs.map} +1 -1
  6. package/dist/address-card-C-NB03XP.cjs +218 -0
  7. package/dist/address-card-LYaT5yz0.mjs +190 -0
  8. package/dist/address-card-LYaT5yz0.mjs.map +1 -0
  9. package/dist/address-risk-DPuXBsvH.cjs +806 -0
  10. package/dist/address-risk-Da6FsfGx.mjs +653 -0
  11. package/dist/address-risk-Da6FsfGx.mjs.map +1 -0
  12. package/dist/{capabilities-Mxa4oQdd.cjs → capabilities-DkNreyv7.cjs} +1 -1
  13. package/dist/{capabilities-bZOr5Ads.mjs → capabilities-w5bNR7F9.mjs} +2 -2
  14. package/dist/{capabilities-bZOr5Ads.mjs.map → capabilities-w5bNR7F9.mjs.map} +1 -1
  15. package/dist/cli.cjs +138 -46
  16. package/dist/cli.mjs +138 -46
  17. package/dist/cli.mjs.map +1 -1
  18. package/dist/{deployer-screen-B5yrXZGo.mjs → deployer-screen-Bkw_sz94.mjs} +3 -3
  19. package/dist/{deployer-screen-B5yrXZGo.mjs.map → deployer-screen-Bkw_sz94.mjs.map} +1 -1
  20. package/dist/{deployer-screen-0SOQ_HFf.cjs → deployer-screen-CFLi7OeH.cjs} +2 -2
  21. package/dist/{dex-registry-BY67f4Ul.mjs → dex-registry-Bkri0--q.mjs} +10 -2
  22. package/dist/{dex-registry-BY67f4Ul.mjs.map → dex-registry-Bkri0--q.mjs.map} +1 -1
  23. package/dist/{dex-registry-BhGJUG9_.cjs → dex-registry-CyR3GyRr.cjs} +20 -0
  24. package/dist/{dex-tool-7BK_gD6H.mjs → dex-tool-D0K_Qx4N.mjs} +4 -4
  25. package/dist/dex-tool-D0K_Qx4N.mjs.map +1 -0
  26. package/dist/{dex-tool-Be9NAuD8.cjs → dex-tool-DQ5Eg0LO.cjs} +3 -3
  27. package/dist/{exchange-deposit-check-C5MseGlZ.cjs → exchange-deposit-check-BNzkwQeW.cjs} +18 -18
  28. package/dist/{exchange-deposit-check-CXHZCHWW.mjs → exchange-deposit-check-DIALj2sm.mjs} +19 -19
  29. package/dist/exchange-deposit-check-DIALj2sm.mjs.map +1 -0
  30. package/dist/{exchange-registry-CT0rRW__.cjs → exchange-registry-CEgkeQV1.cjs} +16 -93
  31. package/dist/{exchange-registry-CoLgHw6d.mjs → exchange-registry-Dr5UtcT5.mjs} +17 -94
  32. package/dist/exchange-registry-Dr5UtcT5.mjs.map +1 -0
  33. package/dist/{exchange-tool-Dc46SJ49.mjs → exchange-tool-B7E29YoQ.mjs} +4 -4
  34. package/dist/exchange-tool-B7E29YoQ.mjs.map +1 -0
  35. package/dist/{exchange-tool-B2SMeC5f.cjs → exchange-tool-CXaUBAd2.cjs} +3 -3
  36. package/dist/{graph-schema-CcrYPpSv.cjs → graph-schema-Bn3txQCj.cjs} +115 -12
  37. package/dist/{graph-schema-CRQuKya1.mjs → graph-schema-DvABR1yl.mjs} +97 -12
  38. package/dist/graph-schema-DvABR1yl.mjs.map +1 -0
  39. package/dist/{layer-routing-YDj-ynG9.cjs → layer-routing-j48SQ8Wk.cjs} +2 -2
  40. package/dist/{layer-routing-DCJVNN6O.mjs → layer-routing-r4IbIQSr.mjs} +3 -3
  41. package/dist/layer-routing-r4IbIQSr.mjs.map +1 -0
  42. package/dist/mcp-proxy.cjs +62 -15
  43. package/dist/mcp-proxy.d.cts.map +1 -1
  44. package/dist/mcp-proxy.d.mts.map +1 -1
  45. package/dist/mcp-proxy.mjs +62 -15
  46. package/dist/mcp-proxy.mjs.map +1 -1
  47. package/dist/public-file-BISyAesm.mjs +133 -0
  48. package/dist/public-file-BISyAesm.mjs.map +1 -0
  49. package/dist/public-file-DDp2CrUl.cjs +138 -0
  50. package/dist/{request-timeout-DxwNijQD.cjs → request-timeout-BXiIt9Jy.cjs} +0 -1
  51. package/dist/{request-timeout-K3ljP0pa.mjs → request-timeout-DetG2xO4.mjs} +2 -2
  52. package/dist/{request-timeout-K3ljP0pa.mjs.map → request-timeout-DetG2xO4.mjs.map} +1 -1
  53. package/dist/{token-lookup-Cf59VdGe.mjs → token-lookup-Ck0q7crJ.mjs} +2 -2
  54. package/dist/{token-lookup-Cf59VdGe.mjs.map → token-lookup-Ck0q7crJ.mjs.map} +1 -1
  55. package/dist/{token-lookup-DqjSRIxd.cjs → token-lookup-DLe4erP9.cjs} +1 -1
  56. package/dist/token-risk-CpMfFRoY.cjs +1004 -0
  57. package/dist/token-risk-DhnJc2kJ.mjs +971 -0
  58. package/dist/token-risk-DhnJc2kJ.mjs.map +1 -0
  59. package/dist/{tool-visibility-D8Up081E.cjs → tool-visibility-BCa-tmyZ.cjs} +11 -2
  60. package/dist/{tool-visibility-DuTds7V4.mjs → tool-visibility-BstrSl4s.mjs} +12 -3
  61. package/dist/tool-visibility-BstrSl4s.mjs.map +1 -0
  62. package/docs/contributing.md +10 -8
  63. package/docs/development.md +5 -5
  64. package/docs/evals.md +16 -1
  65. package/docs/graph-query-compatibility.md +15 -2
  66. package/docs/graph-tools.md +44 -6
  67. package/docs/mcp-proxy.md +189 -8
  68. package/docs/stability.md +4 -5
  69. package/docs/testing.md +76 -0
  70. package/package.json +1 -1
  71. package/registry/README.md +20 -5
  72. package/registry/address-card.json +680 -0
  73. package/skills/chain-insights-address-risk/SKILL.md +61 -0
  74. package/skills/chain-insights-address-risk/agents/openai.yaml +4 -0
  75. package/skills/chain-insights-aml-exchange/SKILL.md +9 -7
  76. package/skills/chain-insights-cypher/SKILL.md +79 -3
  77. package/skills/chain-insights-token-risk/SKILL.md +81 -0
  78. package/skills/chain-insights-token-risk/agents/openai.yaml +4 -0
  79. package/skills/chain-insights-virtuals/reference.md +1 -1
  80. package/dist/dex-tool-7BK_gD6H.mjs.map +0 -1
  81. package/dist/exchange-deposit-check-CXHZCHWW.mjs.map +0 -1
  82. package/dist/exchange-registry-CoLgHw6d.mjs.map +0 -1
  83. package/dist/exchange-tool-Dc46SJ49.mjs.map +0 -1
  84. package/dist/graph-schema-CRQuKya1.mjs.map +0 -1
  85. package/dist/layer-routing-DCJVNN6O.mjs.map +0 -1
  86. package/dist/public-tools-CBszU2oX.cjs +0 -1334
  87. package/dist/public-tools-DVhUjSDV.mjs +0 -1333
  88. package/dist/public-tools-DVhUjSDV.mjs.map +0 -1
  89. package/dist/tool-visibility-DuTds7V4.mjs.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"token-risk-DhnJc2kJ.mjs","names":[],"sources":["../src/mcp/pool-risk.ts","../src/mcp/token-risk.ts"],"sourcesContent":["/**\n * The facts of the pools of a token, and the parties every token risk answer\n * names.\n *\n * A pool row is one ADDRESS. A token trades in pools of two shapes:\n *\n * own address a pool contract with its own :Address node, which carries\n * the pool's card and its liquidity sums;\n * pool manager one address that holds many pools (the manager of a vault\n * exchange in the exchange registry). The graph links each\n * provider to the manager address, so the pools inside it are\n * not told apart: the manager is one row, with its providers\n * and this token's side, and the node's sums (the manager's\n * whole book) are never shown as the pool's.\n *\n * The reads, all on USE topology:\n *\n * providers one read per direction gives the pools, the providers and the\n * adders of a token at once: every ADDED_LIQUIDITY link that\n * carries the token as `asset`, one row per pool and provider,\n * the biggest first, and the same on REMOVED_LIQUIDITY in its own\n * direction (pool to receiver). A whole-chain search: it may be\n * refused or time out on a lane that is behind;\n * node a pool with its own address: its card, its model level and\n * score, and its liquidity sums;\n * parties the 5 biggest adders or removers of one pool, anchored on it,\n * for a pool asked about itself.\n *\n * Every named address is a Party: its risk block is built by the same code as\n * aml_address_risk (src/mcp/address-risk.ts), from its own row. A party never\n * raises the word of a pool or a token: it is shown beside it.\n *\n * A USD figure is the tokens worth at day prices. A sum over links none of\n * which carries a price stays null, never 0.\n */\n\nimport type { AddressCardWord } from './address-card.js'\nimport {\n assertReadAddress,\n kindOf,\n rowRisk,\n type AddressKind,\n type AddressRisk,\n} from './address-risk.js'\nimport { addressOrNull, numberOrNull, strings, textOrNull, utcOrNull } from './row-values.js'\n\n/** The rows a providers read lists at most; a full read means a pool's parties may miss someone. */\nexport const PROVIDERS_READ_LIMIT = 200\n/** The pools a grouped pools read lists at most; a full read means more pools exist. */\nexport const POOLS_READ_LIMIT = 500\n/** The pools detailed (node read, adders and removers), the biggest by tokens added first. */\nexport const POOLS_DETAILED = 10\n/** The adders and the removers kept per pool. */\nexport const POOL_PARTY_LIMIT = 5\n/** The first accounts that paid the founder, oldest first. */\nexport const GAS_WALLET_LIMIT = 3\n\n/** The liquidity sums on a pool node with its own address. */\nexport const POOL_NODE_COLUMNS = [\n 'a.liquidity_added_usd AS liquidity_added_usd',\n 'a.liquidity_removed_usd AS liquidity_removed_usd',\n 'a.liquidity_net_usd AS liquidity_net_usd',\n 'a.provider_count AS provider_count',\n] as const\n\n/** The card and model fields of a party read, on the node `v`. */\nfunction partyColumns(v: string): string {\n return (\n `labels(${v}) AS node_labels, ${v}.identity AS identity, ${v}.identity_name AS identity_name, ` +\n `${v}.identities AS identities, ${v}.evidence AS evidence, ${v}.judgements AS judgements, ` +\n `${v}.risk_level AS risk_level, ${v}.risk_score AS risk_score`\n )\n}\n\n/**\n * The providers of a token on one side, by pool: liquidity added into a pool,\n * or taken off one. One row per pool and provider, the biggest first; a full\n * read (PROVIDERS_READ_LIMIT rows) means more may exist. `priced` counts the\n * links that carry a price.\n */\nexport function tokenProvidersQuery(token: string, side: 'added' | 'removed'): string {\n assertReadAddress(token)\n const match =\n side === 'added'\n ? `(a:Address)-[r:ADDED_LIQUIDITY {asset: \"${token}\"}]->(p:Address)`\n : `(p:Address)-[r:REMOVED_LIQUIDITY {asset: \"${token}\"}]->(a:Address)`\n return (\n `USE topology MATCH ${match} ` +\n 'RETURN p.address AS pool, a.address AS address, sum(r.usd) AS tokens_worth_usd, count(r.usd) AS priced, ' +\n 'sum(r.event_count) AS events, min(r.first_seen_height) AS first_seen_height, ' +\n `max(r.last_seen_height) AS last_seen_height, ${partyColumns('a')} ` +\n `ORDER BY tokens_worth_usd DESC LIMIT ${PROVIDERS_READ_LIMIT}`\n )\n}\n\n/**\n * The pools of a token on one side, one row per pool address: its distinct\n * providers (or removers), this token's USD sum, its priced links and its\n * events. Grouped by the graph, so it counts every pool and every provider up\n * to POOLS_READ_LIMIT pools, where the providers read stops at 200 rows.\n */\nexport function tokenPoolsQuery(token: string, side: 'added' | 'removed'): string {\n assertReadAddress(token)\n const [match, parties] =\n side === 'added'\n ? [`(a:Address)-[r:ADDED_LIQUIDITY {asset: \"${token}\"}]->(p:Address)`, 'providers']\n : [`(p:Address)-[r:REMOVED_LIQUIDITY {asset: \"${token}\"}]->(a:Address)`, 'removers']\n return (\n `USE topology MATCH ${match} ` +\n `RETURN p.address AS pool, count(DISTINCT a) AS ${parties}, sum(r.usd) AS ${side}_usd, ` +\n `count(r.usd) AS priced, sum(r.event_count) AS events ORDER BY ${side}_usd DESC LIMIT ${POOLS_READ_LIMIT}`\n )\n}\n\n/** The biggest adders or removers of one pool address. */\nexport function poolPartiesQuery(pool: string, side: 'adders' | 'removers'): string {\n assertReadAddress(pool)\n const anchor = `(p:Address {address: \"${pool}\"})`\n const match =\n side === 'adders'\n ? `(a:Address)-[r:ADDED_LIQUIDITY]->${anchor}`\n : `${anchor}-[r:REMOVED_LIQUIDITY]->(a:Address)`\n return (\n `USE topology MATCH ${match} ` +\n 'RETURN a.address AS address, sum(r.usd) AS tokens_worth_usd, count(r.usd) AS priced, ' +\n 'sum(r.event_count) AS events, min(r.first_seen_height) AS first_seen_height, ' +\n `max(r.last_seen_height) AS last_seen_height, ${partyColumns('a')} ` +\n `ORDER BY tokens_worth_usd DESC LIMIT ${POOL_PARTY_LIMIT}`\n )\n}\n\n/** The assets added into one pool: its tokens, and NATIVE for the chain's own coin. */\nexport function poolAssetsQuery(pool: string): string {\n assertReadAddress(pool)\n return (\n `USE topology MATCH (a:Address)-[r:ADDED_LIQUIDITY]->(p:Address {address: \"${pool}\"}) ` +\n 'RETURN collect(DISTINCT r.asset) AS assets LIMIT 1'\n )\n}\n\n/** The contract deployment of one address: who deployed it, from which wallet, by which factory. */\nexport function deploymentQuery(address: string): string {\n assertReadAddress(address)\n return (\n `USE topology MATCH (d:Address)-[r:DEPLOYED_CONTRACT]->(t:Address {address: \"${address}\"}) ` +\n 'RETURN d.address AS deployer, r.tx_origin AS tx_origin, r.factory_address AS factory_address, ' +\n 'r.kind AS kind, r.tx_id AS tx_id, r.block_timestamp AS block_timestamp LIMIT 1'\n )\n}\n\n/** The first accounts that paid one wallet, oldest first, with no money floor: a first funder is small on purpose. */\nexport function gasWalletsQuery(founder: string): string {\n assertReadAddress(founder)\n return (\n `USE topology MATCH (s:Account)-[f:FLOWED_TO]->(a:Address {address: \"${founder}\"}) ` +\n 'RETURN s.address AS address, f.amount_usd_sum AS tokens_worth_usd, ' +\n `f.first_seen_timestamp AS first_seen_timestamp, ${partyColumns('s')} ` +\n `ORDER BY f.first_seen_timestamp ASC LIMIT ${GAS_WALLET_LIMIT}`\n )\n}\n\n/** A time in epoch milliseconds, or in seconds, as UTC text; null for anything else. */\nexport function timeText(value: unknown): string | null {\n const number = numberOrNull(value)\n if (number === null) return null\n return utcOrNull(number) ?? utcOrNull(number * 1000)\n}\n\n/** A USD sum of a read, or null when no link of it carried a price. */\nexport function usdOf(row: Record<string, unknown> | undefined, column: string): number | null {\n const sum = numberOrNull(row?.[column])\n const priced = numberOrNull(row?.priced)\n if (priced !== null && priced <= 0) return null\n return sum\n}\n\nexport type PartyRole =\n 'founder' | 'factory' | 'gas_wallet' | 'adder' | 'remover' | 'deployer' | 'token'\n\n/** A named address of an answer, with its own risk block. */\nexport interface Party {\n role: PartyRole\n address: string\n /** What this address moved in its role, tokens worth USD at day prices; null when unpriced. */\n tokens_worth_usd?: number | null\n risk: AddressRisk\n kind: AddressKind\n identity: { word: string; name: string | null } | null\n /** A gas wallet: when it first paid the founder. */\n first_seen_utc?: string | null\n /** An adder or a remover: its liquidity events and the blocks of the first and the last. */\n events?: number | null\n first_seen_height?: number | null\n last_seen_height?: number | null\n}\n\n/** The party of one row: its risk block by the address rule, its kind and its identity. */\nexport function partyOf(\n role: PartyRole,\n address: string,\n row: Record<string, unknown> | undefined,\n dictionary: readonly AddressCardWord[],\n extra: Partial<\n Pick<\n Party,\n 'tokens_worth_usd' | 'first_seen_utc' | 'events' | 'first_seen_height' | 'last_seen_height'\n >\n > = {}\n): Party {\n const word = textOrNull(row?.identity)\n return {\n role,\n address,\n ...('tokens_worth_usd' in extra ? { tokens_worth_usd: extra.tokens_worth_usd ?? null } : {}),\n risk: { ...rowRisk(row, dictionary), card_version: textOrNull(row?.card_version) },\n kind: kindOf(strings(row?.node_labels)),\n identity: word ? { word, name: textOrNull(row?.identity_name) } : null,\n ...('first_seen_utc' in extra ? { first_seen_utc: extra.first_seen_utc ?? null } : {}),\n ...('events' in extra ? { events: extra.events ?? null } : {}),\n ...('first_seen_height' in extra ? { first_seen_height: extra.first_seen_height ?? null } : {}),\n ...('last_seen_height' in extra ? { last_seen_height: extra.last_seen_height ?? null } : {}),\n }\n}\n\n/** The adders or removers of one pool read, as parties. */\nexport function poolPartiesOf(\n role: 'adder' | 'remover',\n rows: Array<Record<string, unknown>>,\n dictionary: readonly AddressCardWord[]\n): Party[] {\n const parties: Party[] = []\n for (const row of rows.slice(0, POOL_PARTY_LIMIT)) {\n const address = addressOrNull(row.address)\n if (!address) continue\n parties.push(\n partyOf(role, address, row, dictionary, {\n tokens_worth_usd: usdOf(row, 'tokens_worth_usd'),\n events: numberOrNull(row.events),\n first_seen_height: numberOrNull(row.first_seen_height),\n last_seen_height: numberOrNull(row.last_seen_height),\n })\n )\n }\n return parties\n}\n\n/** One pool address of a token, as its two providers reads list it. */\nexport interface PoolListing {\n pool: string\n /** Distinct adders of this token into the pool: by the grouped pools read, else among the rows read. */\n providers: number\n /** This token's side: added and removed, tokens worth USD; null when unpriced or not read. */\n added_usd: number | null\n removed_usd: number | null\n adder_rows: Array<Record<string, unknown>>\n remover_rows: Array<Record<string, unknown>>\n}\n\n/** The sum of the priced rows' USD, or null when no row carried a price. */\nfunction pricedSum(rows: Array<Record<string, unknown>>): number | null {\n let sum: number | null = null\n for (const row of rows) {\n const usd = usdOf(row, 'tokens_worth_usd')\n if (usd !== null) sum = (sum ?? 0) + usd\n }\n return sum\n}\n\n/**\n * The pool addresses of a token from its two providers reads, the biggest by\n * this token added first. A removed sum is 0 for a pool with no removal row\n * in a removals read that answered with fewer than PROVIDERS_READ_LIMIT rows\n * (nothing removed). It is null when the read did not answer (`removed` is\n * null), when it came back full (more rows may exist), or when the pool's\n * removal rows carry no price.\n */\nexport function poolListingsOf(\n added: Array<Record<string, unknown>>,\n removed: Array<Record<string, unknown>> | null\n): PoolListing[] {\n const byPool = new Map<\n string,\n { adders: Array<Record<string, unknown>>; removers: Array<Record<string, unknown>> }\n >()\n const entry = (pool: string) => {\n const known = byPool.get(pool) ?? { adders: [], removers: [] }\n byPool.set(pool, known)\n return known\n }\n for (const row of added) {\n const pool = addressOrNull(row.pool)\n if (pool && addressOrNull(row.address)) entry(pool).adders.push(row)\n }\n for (const row of removed ?? []) {\n const pool = addressOrNull(row.pool)\n if (pool && addressOrNull(row.address)) entry(pool).removers.push(row)\n }\n const listings: PoolListing[] = [...byPool].map(([pool, rows]) => ({\n pool,\n providers: new Set(rows.adders.map((row) => addressOrNull(row.address))).size,\n added_usd: pricedSum(rows.adders),\n // No removal row in a read that answered whole is nothing removed: 0, not unknown.\n removed_usd:\n removed === null\n ? null\n : rows.removers.length === 0 && removed.length < PROVIDERS_READ_LIMIT\n ? 0\n : pricedSum(rows.removers),\n adder_rows: rows.adders,\n remover_rows: rows.removers,\n }))\n const rank = (value: number | null) => (value === null ? -1 : value)\n return listings.sort(\n (a, b) => rank(b.added_usd) - rank(a.added_usd) || a.pool.localeCompare(b.pool)\n )\n}\n\n/**\n * The pool addresses of a token from its two grouped pools reads: providers\n * and this token's side come from the groups, the parties of each pool from\n * the providers rows. `removedGroups` is null when the grouped removals read\n * did not answer: every removed sum is then null. A pool with no removal group\n * in a grouped read under POOLS_READ_LIMIT rows removed nothing (0); a group\n * whose links carry no price is null. `addedRows` and `removedRows` are null\n * when that providers read did not answer: the pool then has no parties.\n */\nexport function poolListingsFromGroups(\n addedGroups: Array<Record<string, unknown>>,\n removedGroups: Array<Record<string, unknown>> | null,\n addedRows: Array<Record<string, unknown>> | null,\n removedRows: Array<Record<string, unknown>> | null\n): PoolListing[] {\n const removedBy = new Map<string, Record<string, unknown>>()\n for (const row of removedGroups ?? []) {\n const pool = addressOrNull(row.pool)\n if (pool) removedBy.set(pool, row)\n }\n const rowsBy = (rows: Array<Record<string, unknown>> | null) => {\n const by = new Map<string, Array<Record<string, unknown>>>()\n for (const row of rows ?? []) {\n const pool = addressOrNull(row.pool)\n if (!pool || !addressOrNull(row.address)) continue\n by.set(pool, [...(by.get(pool) ?? []), row])\n }\n return by\n }\n const adderRows = rowsBy(addedRows)\n const removerRows = rowsBy(removedRows)\n const removedFull = (removedGroups?.length ?? 0) >= POOLS_READ_LIMIT\n const listings: PoolListing[] = []\n const seen = new Set<string>()\n const push = (pool: string, added: Record<string, unknown> | null) => {\n if (seen.has(pool)) return\n seen.add(pool)\n const removed = removedBy.get(pool)\n listings.push({\n pool,\n providers: numberOrNull(added?.providers) ?? 0,\n added_usd: added ? usdOf(added, 'added_usd') : null,\n removed_usd:\n removedGroups === null\n ? null\n : removed\n ? usdOf(removed, 'removed_usd')\n : removedFull\n ? null\n : 0,\n adder_rows: adderRows.get(pool) ?? [],\n remover_rows: removerRows.get(pool) ?? [],\n })\n }\n for (const row of addedGroups) {\n const pool = addressOrNull(row.pool)\n if (pool) push(pool, row)\n }\n for (const pool of removedBy.keys()) push(pool, null)\n const rank = (value: number | null) => (value === null ? -1 : value)\n return listings.sort((a, b) => rank(b.added_usd) - rank(a.added_usd) || a.pool.localeCompare(b.pool))\n}\n\nexport interface PoolLiquidity {\n added_usd: number | null\n removed_usd: number | null\n net_usd: number | null\n}\n\n/** The facts of one pool address. */\nexport interface PoolFacts {\n pool: string\n /** The exchange's name in the exchange registry, by its factory or its manager; null when unknown. */\n exchange: string | null\n /** A pool manager: its pools inside are answered as this one row. */\n is_manager: boolean\n /** A pool manager only: the pools inside it, which the graph does not tell apart. */\n pools_inside?: null\n /** True for the biggest pools: their node read and their parties. */\n detail: boolean\n /** Distinct liquidity providers: of this token, or of the pool asked about. */\n providers: number | null\n /** This token's side of the pool, tokens worth USD; null in a pool answer. */\n token_side: { added_usd: number | null; removed_usd: number | null } | null\n /** Both sides of a pool with its own address, from its node; null for a manager and when not read. */\n liquidity: PoolLiquidity | null\n /** The pool's own risk block; null for a manager, and when not read. */\n risk: AddressRisk | null\n adders: Party[]\n removers: Party[]\n}\n\n/**\n * The facts of one pool address. A pool with its own address takes both sides\n * of its liquidity and its word from its node; a manager takes neither (its\n * node is its whole book) and shows this token's side only.\n */\nexport function poolFactsOf(input: {\n pool: string\n exchange: string | null\n isManager: boolean\n detail: boolean\n providers: number | null\n tokenSide: PoolFacts['token_side']\n node: Record<string, unknown> | null\n adders: Party[]\n removers: Party[]\n dictionary: readonly AddressCardWord[]\n}): PoolFacts {\n const { node } = input\n const own = !input.isManager && node !== null\n let liquidity: PoolLiquidity | null = null\n if (own) {\n const added = numberOrNull(node.liquidity_added_usd)\n const removed = numberOrNull(node.liquidity_removed_usd)\n const net =\n numberOrNull(node.liquidity_net_usd) ??\n (added !== null && removed !== null ? added - removed : null)\n liquidity = { added_usd: added, removed_usd: removed, net_usd: net }\n }\n return {\n pool: input.pool,\n exchange: input.exchange,\n is_manager: input.isManager,\n ...(input.isManager ? { pools_inside: null } : {}),\n detail: input.detail,\n providers: input.providers,\n token_side: input.tokenSide,\n liquidity,\n risk: own\n ? { ...rowRisk(node, input.dictionary), card_version: textOrNull(node.card_version) }\n : null,\n adders: input.adders,\n removers: input.removers,\n }\n}\n","/**\n * aml_token_risk: what about this token, or this pool?\n *\n * A local tool of the proxy, built on the address answer of aml_address_risk.\n * At most four graph_query_batch calls, one after another, each of at most 20\n * reads, all on USE topology:\n *\n * 1 the subject's node alone (card, model, token facts, pool sums, link\n * count): not found, or a wallet, ends here;\n * 2 its money senders and receivers (never for a hub, more than HUB_DEGREE\n * links), its deployment, and its pool parts and assets;\n * 3 a token: its pools and providers (four whole-chain reads by asset,\n * first in the batch), its founder (the full address answer), its\n * factory and the founder's gas wallets. A pool: its tokens and its\n * deployer;\n * 4 a token: the node and the deployment of each of the 10 biggest pools\n * that has its own address. A pool manager is one row and is not read.\n *\n * The founder is the wallet that sent the deployment (`tx_origin`), never the\n * factory contract every launchpad token shares. The token's word is the\n * highest of the token's own, the founder's and each detailed pool's own; a\n * pool manager, a factory, a gas wallet, an adder and a remover carry their\n * own word or none and never raise it. A part that was not read is named in not_read and never shown as\n * \"none found\".\n *\n * The tool states, the host judges: no hint, no summary, no verdict. The only\n * prose is each reason's fixed plain sentence from the card dictionary.\n */\n\nimport type { AddressCardWord, LoadedAddressCard } from './address-card.js'\nimport {\n ADDRESS_INPUT,\n SURROUNDINGS_NODE_LIMIT,\n hubDegreeOf,\n addressNodeQuery,\n addressPartnerQuery,\n addressRiskFromMembers,\n type AddressKind,\n type AddressRisk,\n type AmlAddressRiskResult,\n type ExchangeEnd,\n type Exposure,\n type ModelScore,\n type SurroundingsLink,\n type SurroundingsNode,\n} from './address-risk.js'\nimport {\n DexRegistryError,\n dexManagerOf,\n dexOfAddress,\n normalizeDexNetwork,\n type DexEntry,\n type LoadedRegistry,\n} from './dex-registry.js'\nimport type { ExchangeEntry, LoadedExchangeRegistry } from './exchange-registry.js'\nimport {\n POOLS_DETAILED,\n POOL_NODE_COLUMNS,\n POOLS_READ_LIMIT,\n PROVIDERS_READ_LIMIT,\n deploymentQuery,\n gasWalletsQuery,\n partyOf,\n poolAssetsQuery,\n poolFactsOf,\n poolListingsFromGroups,\n poolListingsOf,\n poolPartiesOf,\n poolPartiesQuery,\n timeText,\n tokenPoolsQuery,\n tokenProvidersQuery,\n type Party,\n type PoolFacts,\n type PoolListing,\n} from './pool-risk.js'\nimport { riskWordRank, splitCardEntry, type RiskWord, type SetBy } from './risk-word.js'\nimport {\n addressOrNull,\n isRecord,\n memberAnswered,\n memberRefusal,\n memberRows,\n numberOrNull,\n strings,\n textOrNull,\n utcOrNull,\n} from './row-values.js'\nimport { membersOf, refusalOf, type GraphAnswer, type Member } from './token-lookup.js'\n\nexport const AML_TOKEN_RISK_TOOL = 'aml_token_risk' as const\nexport const AML_TOKEN_RISK_SCHEMA = 'chain-insights.aml-token-risk.v1' as const\nexport const AML_TOKEN_RISK_TITLE = 'Token risk'\n\nexport const TOKEN_RISK_READING_RULE =\n 'The tool states facts and measures; you write the judgement: say which reasons and whose word you rely on, ' +\n 'say when a word comes from the model alone (set_by model) that it is a prediction, never call a token or a pool safe, ' +\n 'and name a part listed in not_read as not read, never as none found.'\n\nexport const AML_TOKEN_RISK_DESCRIPTION =\n 'Answers what is known about one token contract or one pool: the token and how it was deployed, its founder (the wallet that sent the deployment, with its own risk answer and money partners), ' +\n 'the factory or launchpad that deployed it (such as Virtuals; factory.name comes from the exchange registry, or from the token launchpad identity, and named_by says which), the first accounts that paid the founder (gas wallets), and its pools with their liquidity, their 5 biggest adders and removers. ' +\n 'A wallet is no token: ask aml_address_risk about a wallet. A ticker is no address: call meta_token_lookup first. ' +\n 'risk.word is the highest of the token own word, its founder word and each detailed pool own word, and raised_by says whose (raised_by_address names it); risk.own is the token own risk block. ' +\n 'A factory or launchpad, a first funder and a liquidity provider never raise the word: each carries its own beside it. ' +\n 'Every word is the higher of what labels prove and what the risk model predicts; unscored is not low and not safe. ' +\n 'A pool row is one address: the pools inside one pool manager (such as Uniswap v4) are answered as one row for the manager (is_manager true), with its providers and this token side, not pool by pool; a manager row carries no word and never raises it, and a manager asked about itself lists no adders, removers or tokens (pool_tokens is empty): its parties and its tokens are answered per token, so ask the token. ' +\n 'pools_found counts every pool address of the token (up to 500); only the 10 biggest are detailed (detail true), pools_truncated says when more exist; providers and token_side count every provider of a pool; parties_truncated says the 5 biggest adders and removers of a pool may miss a party. ' +\n 'A part listed in not_read was not read: it is never \"none found\". ' +\n `${TOKEN_RISK_READING_RULE} ` +\n 'USD figures are tokens worth at day prices; null is unpriced, never 0. Write every address in full, all 42 characters. ' +\n 'A hub (more than 50,000 links, such as the zero address or a pool manager) has its counterparties not ranked: exposure.hub is true and not_read names counterparties; ask about one counterparty, or one token, instead. ' +\n 'Pass surroundings: true for the nodes and links behind the answer, to draw.'\n\nexport const AML_TOKEN_RISK_ANNOTATIONS = {\n readOnlyHint: true,\n idempotentHint: true,\n openWorldHint: false,\n} as const\nexport const AML_TOKEN_RISK_ARGS = ['network', 'address', 'surroundings'] as const\n\n/** The most batches one answer sends, and the most reads in one batch. */\nexport const BATCH_LIMIT = 4\nexport const BATCH_MEMBER_LIMIT = 20\n\n/** A token's node read adds its facts and, for a pool, its sums. */\nconst SUBJECT_COLUMNS = [\n 'a.token_standard AS token_standard',\n 'a.contract_creation_timestamp AS contract_creation_timestamp',\n ...POOL_NODE_COLUMNS,\n]\n\nexport type AskedAs = 'token' | 'pool' | 'address'\nexport type RaisedBy = 'token' | 'founder' | 'pool'\n\nexport interface TokenRisk {\n word: RiskWord\n /** Who set the word of the party that raised it: rules, model, both; none when unscored. */\n set_by: SetBy\n /** The subject's own model score, or null. */\n score: number | null\n raised_by: RaisedBy | null\n raised_by_address: string | null\n /** The subject's own risk block. */\n own: AddressRisk\n}\n\nexport interface TokenNotRead {\n part: string\n code: string\n reason: string\n /** A part of one pool: the pool address. */\n pool?: string\n}\n\nexport type FounderParty = Party & { exposure: Exposure | null; exchange_ends: ExchangeEnd[] }\nexport type FactoryParty = Party & {\n name: string | null\n /** How the name was found: the exchange registry row of the factory, the token's launchpad identity, or null when unnamed. */\n named_by: 'registry' | 'launchpad' | null\n}\n\n/**\n * The exchange registry key of a token's launchpad identity: the first part\n * of a `launchpad` card value (`virtuals:CIA:graduated` gives `virtuals`),\n * from its identity or any entry of its identities. Null when it has none.\n */\nexport function launchpadKeyOf(row: Record<string, unknown> | undefined): string | null {\n const values: string[] = []\n if (textOrNull(row?.identity) === 'launchpad') {\n const name = textOrNull(row?.identity_name)\n if (name) values.push(name)\n }\n for (const entry of strings(row?.identities)) {\n const { word, value } = splitCardEntry(entry)\n if (word === 'launchpad' && value) values.push(value)\n }\n for (const value of values) {\n const key = value.split(':')[0]?.trim().toLowerCase()\n if (key) return key\n }\n return null\n}\n\n/**\n * The name of a token's factory: its exchange registry row by address; else,\n * a token factory with no row of its own (it creates tokens, not pools), the\n * registry's name for the token's launchpad identity; else none.\n */\nexport function factoryNameOf(\n factory: string,\n tokenRow: Record<string, unknown> | undefined,\n dexRows: readonly DexEntry[]\n): Pick<FactoryParty, 'name' | 'named_by'> {\n const row = dexOfAddress(factory, dexRows)\n if (row) return { name: row.display, named_by: 'registry' }\n const key = launchpadKeyOf(tokenRow)\n const launchpad = key ? dexRows.find((entry) => entry.dex === key) : undefined\n if (launchpad) return { name: launchpad.display, named_by: 'launchpad' }\n return { name: null, named_by: null }\n}\n\nexport interface TokenSurroundingsNode extends Omit<SurroundingsNode, 'role'> {\n role:\n | 'subject'\n | 'founder'\n | 'factory'\n | 'deployer'\n | 'gas_wallet'\n | 'pool'\n | 'adder'\n | 'remover'\n | 'partner'\n | 'exchange_end'\n}\n\nexport interface TokenSurroundingsLink extends Omit<SurroundingsLink, 'link'> {\n link: 'FLOWED_TO' | 'DEPLOYED_CONTRACT' | 'ADDED_LIQUIDITY' | 'REMOVED_LIQUIDITY'\n}\n\nexport interface AmlTokenRiskResult {\n schema: typeof AML_TOKEN_RISK_SCHEMA\n tool: typeof AML_TOKEN_RISK_TOOL\n network: string\n address: string\n asked_as: AskedAs\n found: boolean\n token: {\n address: string\n standard: string | null\n created_utc: string | null\n identity: { word: string; name: string | null } | null\n } | null\n risk: TokenRisk\n model: ModelScore\n founder: FounderParty | null\n factory: FactoryParty | null\n deployment: { tx_id: string | null; created_utc: string | null; kind: string | null } | null\n gas_wallets: Party[]\n pools: PoolFacts[]\n /** Every pool address read; null when the providers read did not answer. */\n pools_found: number | null\n pools_truncated: boolean\n /** True when a providers rows read came back full: a pool's adders or removers may miss a party. */\n parties_truncated: boolean\n /** A pool answer: the tokens of the pool. */\n pool_tokens: Party[]\n /** A pool answer: the wallet that deployed the pool. */\n deployer: Party | null\n exposure: Exposure | null\n exchange_ends: ExchangeEnd[]\n not_read: TokenNotRead[]\n surroundings?: {\n nodes: TokenSurroundingsNode[]\n links: TokenSurroundingsLink[]\n truncated: boolean\n }\n}\n\nexport interface TokenRiskDependencies {\n loadAddressCard: () => Promise<LoadedAddressCard | null>\n loadExchangeRegistry: (network: string) => Promise<LoadedExchangeRegistry>\n /** The exchange registry: it names a factory. */\n loadDexRegistry: (network: string) => Promise<LoadedRegistry>\n graphQueryBatch: (args: {\n network: string\n queries: Array<{ id: string; query: string }>\n }) => Promise<GraphAnswer>\n unavailable?: () => Promise<string | undefined> | string | undefined\n describeFailure: (err: unknown) => string\n}\n\nexport type AmlTokenRiskToolResult = {\n content: Array<{ type: 'text'; text: string }>\n structuredContent?: Record<string, unknown>\n isError: boolean\n}\n\n/** What the node labels make of the subject: a launchpad pair carries Token and Pool, and Pool wins. */\nexport function askedAsOf(nodeLabels: readonly string[]): AskedAs {\n if (nodeLabels.includes('Pool')) return 'pool'\n if (nodeLabels.includes('Token')) return 'token'\n return 'address'\n}\n\n/** The deployment of a contract: its founder (tx_origin, else the deployer) and its factory. */\nexport interface Deployment {\n deployer: string | null\n /** The factory the deployment names, whoever sent it. */\n factory_address: string | null\n founder: string | null\n factory: string | null\n tx_id: string | null\n kind: string | null\n created_utc: string | null\n}\n\nexport function deploymentOf(row: Record<string, unknown> | undefined): Deployment | null {\n if (!row) return null\n const deployer = addressOrNull(row.deployer)\n const founder = addressOrNull(row.tx_origin) ?? deployer\n const kind = textOrNull(row.kind)\n const factoryAddress = addressOrNull(row.factory_address)\n const factory =\n kind?.toLowerCase() === 'factory' && factoryAddress !== null && factoryAddress !== founder\n ? factoryAddress\n : null\n return {\n deployer,\n factory_address: factoryAddress,\n founder,\n factory,\n tx_id: textOrNull(row.tx_id),\n kind,\n created_utc: timeText(row.block_timestamp),\n }\n}\n\n/** The word of an answer: the highest of the candidates, the first on a tie; unscored when none speaks. */\nexport type Candidate = { by: RaisedBy; address: string; risk: AddressRisk }\n\nexport function raisedWordOf(own: AddressRisk, candidates: Candidate[]): TokenRisk {\n let best: Candidate | null = null\n for (const candidate of candidates) {\n if (candidate.risk.word === 'unscored') continue\n if (!best || riskWordRank(candidate.risk.word) > riskWordRank(best.risk.word)) best = candidate\n }\n return {\n word: best?.risk.word ?? 'unscored',\n set_by: best?.risk.set_by ?? 'none',\n score: own.score,\n raised_by: best?.by ?? null,\n raised_by_address: best?.address ?? null,\n own,\n }\n}\n\ntype Batch = Array<{ id: string; query: string }>\n\n/** Sends one batch; a call that throws or holds no reads answers every read as not read, with why. */\nasync function sendBatch(\n deps: TokenRiskDependencies,\n network: string,\n queries: Batch\n): Promise<Map<string, Member>> {\n let answer: GraphAnswer\n try {\n answer = await deps.graphQueryBatch({ network, queries })\n } catch (err) {\n return failedMembers(queries, deps.describeFailure(err))\n }\n const members = membersOf(answer)\n if (members.size > 0) return members\n const text = answer.isError === true ? refusalOf(answer).text : 'the batch answer held no reads'\n return failedMembers(queries, text)\n}\n\nfunction failedMembers(queries: Batch, error: string): Map<string, Member> {\n return new Map(queries.map(({ id }) => [id, { id, ok: false, error }]))\n}\n\nconst poolId = (index: number, part: 'node' | 'deployment') => `pool${index}_${part}`\n\nfunction errorResult(text: string): AmlTokenRiskToolResult {\n return { content: [{ type: 'text', text }], isError: true }\n}\n\nfunction textResult(structured: AmlTokenRiskResult): AmlTokenRiskToolResult {\n return {\n content: [{ type: 'text', text: JSON.stringify(structured, null, 2) }],\n structuredContent: structured as unknown as Record<string, unknown>,\n isError: false,\n }\n}\n\n/** The answer's not-read entry of one member, or null when it answered. */\nfunction notReadOf(\n part: string,\n id: string,\n members: Map<string, Member>,\n pool?: string\n): TokenNotRead | null {\n const member = members.get(id)\n if (memberAnswered(member)) return null\n return { part, ...memberRefusal(id, member), ...(pool ? { pool } : {}) }\n}\n\n/** The founder party from its full address answer. */\nfunction founderOf(address: string, answer: AmlAddressRiskResult): FounderParty {\n return {\n role: 'founder',\n address,\n risk: answer.risk,\n kind: answer.kind,\n identity: answer.identity,\n exposure: answer.exposure,\n exchange_ends: answer.exchange_ends,\n }\n}\n\n/** aml_token_risk, {network, address, surroundings?}. Every argument is checked before a read is sent. */\nexport async function handleAmlTokenRisk(\n args: unknown,\n deps: TokenRiskDependencies\n): Promise<AmlTokenRiskToolResult> {\n const record = isRecord(args) ? args : {}\n let network: string\n try {\n network = normalizeDexNetwork(record.network)\n } catch (err) {\n return errorResult(\n err instanceof DexRegistryError ? err.message : `invalid_network: ${(err as Error).message}`\n )\n }\n const raw = typeof record.address === 'string' ? record.address.trim() : ''\n if (!ADDRESS_INPUT.test(raw)) {\n return errorResult(\n 'invalid_address: address is required: the token contract or the pool, 0x plus 40 hex characters. ' +\n 'A ticker or a name is not an address: call meta_token_lookup first.'\n )\n }\n if (record.surroundings !== undefined && typeof record.surroundings !== 'boolean') {\n return errorResult('invalid_surroundings: surroundings is true or false.')\n }\n const address = raw.toLowerCase()\n const drawing = record.surroundings === true\n\n const unavailable = await deps.unavailable?.()\n if (unavailable) {\n return errorResult(\n `No token risk read was sent: ${unavailable} There is no answer yet, which is not \"no risk\": try again later.`\n )\n }\n\n let dictionary: readonly AddressCardWord[]\n try {\n const card = await deps.loadAddressCard()\n if (!card) throw new Error('no copy of the address card dictionary is available')\n dictionary = card.document.words\n } catch (err) {\n return errorResult(\n `No token risk read was sent: the address card dictionary did not load (${(err as Error).message}). ` +\n 'There is no answer yet, which is not \"no risk\".'\n )\n }\n let exchangeRows: ExchangeEntry[] = []\n try {\n exchangeRows = (await deps.loadExchangeRegistry(network)).document.rows\n } catch {\n // The lookup only names an exchange wallet; the graph reads still answer.\n }\n let dexRows: DexEntry[] = []\n try {\n dexRows = (await deps.loadDexRegistry(network)).document.rows\n } catch {\n // The registry only names a factory.\n }\n\n // Call 1: the subject node alone (about 50 ms): found or not, what it is, and whether it is a hub.\n let answer: GraphAnswer\n try {\n answer = await deps.graphQueryBatch({\n network,\n queries: [{ id: 'node', query: addressNodeQuery(address, SUBJECT_COLUMNS) }],\n })\n } catch (err) {\n return errorResult(\n `The token risk read failed: ${deps.describeFailure(err)} This is not \"no risk\": send the same call again once.`\n )\n }\n const members1 = membersOf(answer)\n if (members1.size === 0) {\n const text = answer.isError === true ? refusalOf(answer).text : 'the batch answer held no reads'\n return errorResult(`The token risk read failed: ${text} This is not \"no risk\".`)\n }\n const nodeMember = members1.get('node')\n if (!memberAnswered(nodeMember)) {\n return errorResult(\n `The token risk read failed: ${memberRefusal('node', nodeMember).reason} This is not \"no risk\": send the same call again once.`\n )\n }\n const nodeRow = memberRows(nodeMember)[0]\n const isManager = dexManagerOf(address, dexRows) !== null\n // A pool manager of the exchange registry is asked as a pool: the graph labels no manager :Pool.\n const askedAs: AskedAs = !nodeRow\n ? 'address'\n : isManager\n ? 'pool'\n : askedAsOf(strings(nodeRow.node_labels))\n\n // Call 2, for a token or a pool: its money partners (never for a hub), its deployment and its pool parts.\n if (askedAs !== 'address') {\n const hub = hubDegreeOf(nodeRow) !== null\n const rest: Batch = [\n ...(hub\n ? []\n : [\n { id: 'in', query: addressPartnerQuery(address, 'in') },\n { id: 'out', query: addressPartnerQuery(address, 'out') },\n ]),\n { id: 'deployment', query: deploymentQuery(address) },\n // A pool manager's parties and tokens span its whole book, and the reads time out (24 s on the\n // Uniswap v4 manager): they are answered per token.\n ...(isManager\n ? []\n : [\n { id: 'adders', query: poolPartiesQuery(address, 'adders') },\n { id: 'removers', query: poolPartiesQuery(address, 'removers') },\n { id: 'assets', query: poolAssetsQuery(address) },\n ]),\n ]\n for (const [id, member] of await sendBatch(deps, network, rest)) members1.set(id, member)\n }\n const subjectBuilt = addressRiskFromMembers(\n network,\n address,\n members1,\n dictionary,\n exchangeRows,\n '',\n {\n surroundings: drawing,\n hubGuard: true,\n }\n )\n if ('failure' in subjectBuilt) {\n return errorResult(\n `The token risk read failed: ${subjectBuilt.failure} This is not \"no risk\": send the same call again once.`\n )\n }\n const subject = subjectBuilt.result\n const notRead: TokenNotRead[] = subject.not_read.map((entry) => ({ ...entry }))\n\n const base: AmlTokenRiskResult = {\n schema: AML_TOKEN_RISK_SCHEMA,\n tool: AML_TOKEN_RISK_TOOL,\n network,\n address,\n asked_as: askedAs,\n found: subject.found,\n token: null,\n // A wallet or an address not found: its own word, raised by nobody else.\n risk: {\n ...raisedWordOf(subject.risk, []),\n word: subject.risk.word,\n set_by: subject.risk.set_by,\n },\n model: subject.model,\n founder: null,\n factory: null,\n deployment: null,\n gas_wallets: [],\n pools: [],\n pools_found: null,\n pools_truncated: false,\n parties_truncated: false,\n pool_tokens: [],\n deployer: null,\n exposure: null,\n exchange_ends: [],\n not_read: [],\n }\n if (askedAs === 'address') {\n // A wallet belongs to aml_address_risk: its own word, and nothing else read here.\n return textResult(base)\n }\n\n const deployment = deploymentOf(memberRows(members1.get('deployment'))[0])\n const deploymentMissing = notReadOf('deployment', 'deployment', members1)\n if (deploymentMissing) notRead.push(deploymentMissing)\n\n const result: AmlTokenRiskResult = {\n ...base,\n exposure: subject.exposure,\n exchange_ends: subject.exchange_ends,\n deployment: deployment\n ? { tx_id: deployment.tx_id, created_utc: deployment.created_utc, kind: deployment.kind }\n : null,\n }\n const graph = new SurroundingsBuilder(drawing ? subject : null)\n\n if (askedAs === 'pool') {\n await answerPool({\n deps,\n network,\n address,\n members1,\n dictionary,\n dexRows,\n deployment,\n notRead,\n result,\n graph,\n subject,\n })\n } else {\n await answerToken({\n deps,\n network,\n address,\n dictionary,\n exchangeRows,\n dexRows,\n deployment,\n notRead,\n result,\n graph,\n subject,\n nodeRow: nodeRow!,\n })\n }\n result.not_read = notRead\n if (drawing) result.surroundings = graph.build()\n return textResult(result)\n}\n\ninterface Step {\n deps: TokenRiskDependencies\n network: string\n address: string\n dictionary: readonly AddressCardWord[]\n dexRows: DexEntry[]\n deployment: Deployment | null\n notRead: TokenNotRead[]\n result: AmlTokenRiskResult\n graph: SurroundingsBuilder\n subject: AmlAddressRiskResult\n}\n\n/** The exchange of a pool address: the manager's exchange, else its deployer's or factory's, else null. */\nfunction exchangeOf(\n pool: string,\n deployment: Deployment | null,\n dexRows: readonly DexEntry[]\n): string | null {\n const by = [pool, deployment?.deployer ?? null, deployment?.factory_address ?? null]\n const manager = dexManagerOf(pool, dexRows)\n if (manager) return manager.display\n for (const address of by) {\n if (address === null) continue\n const row = dexOfAddress(address, dexRows)\n if (row) return row.display\n }\n return null\n}\n\n/** A pool: its own word, its sums and parties from batch 1, its tokens and deployer from batch 2. */\nasync function answerPool(step: Step & { members1: Map<string, Member> }): Promise<void> {\n const {\n deps,\n network,\n address,\n members1,\n dictionary,\n dexRows,\n deployment,\n notRead,\n result,\n graph,\n subject,\n } = step\n const isManager = dexManagerOf(address, dexRows) !== null\n // A manager's parties are not read here (ask the token): none listed, and nothing named as not read.\n const adders = isManager\n ? []\n : poolPartiesOf('adder', memberRows(members1.get('adders')), dictionary)\n const removers = isManager\n ? []\n : poolPartiesOf('remover', memberRows(members1.get('removers')), dictionary)\n const parts: Array<readonly [string, string]> = [\n ...(isManager\n ? []\n : ([\n ['adders', 'adders'],\n ['removers', 'removers'],\n ['tokens', 'assets'],\n ] as const)),\n ]\n for (const [part, id] of parts) {\n const missing = notReadOf(part, id, members1)\n if (missing) notRead.push(missing)\n }\n const nodeRow = memberRows(members1.get('node'))[0] ?? null\n const facts = poolFactsOf({\n pool: address,\n exchange: exchangeOf(address, deployment, dexRows),\n isManager,\n detail: true,\n providers: numberOrNull(nodeRow?.provider_count),\n tokenSide: null,\n node: nodeRow,\n adders,\n removers,\n dictionary,\n })\n result.pools = [facts]\n result.pools_found = 1\n // A pool answers with its own word; a pool manager's word raises nothing.\n result.risk = isManager\n ? { ...raisedWordOf(subject.risk, []), word: subject.risk.word, set_by: subject.risk.set_by }\n : raisedWordOf(subject.risk, [{ by: 'pool', address, risk: subject.risk }])\n\n const tokens = strings(memberRows(members1.get('assets'))[0]?.assets)\n .map((asset) => addressOrNull(asset))\n .filter((asset): asset is string => asset !== null && asset !== address)\n .slice(0, 2)\n const deployerAddress = deployment?.founder ?? null\n const second: Batch = [\n ...tokens.map((token, index) => ({ id: `token${index}_node`, query: addressNodeQuery(token) })),\n ...(deployerAddress ? [{ id: 'deployer_node', query: addressNodeQuery(deployerAddress) }] : []),\n ]\n if (second.length > 0) {\n const members2 = await sendBatch(deps, network, second)\n tokens.forEach((token, index) => {\n const id = `token${index}_node`\n const missing = notReadOf('token', id, members2)\n if (missing) notRead.push(missing)\n else\n result.pool_tokens.push(\n partyOf('token', token, memberRows(members2.get(id))[0], dictionary)\n )\n })\n if (deployerAddress) {\n const missing = notReadOf('deployer', 'deployer_node', members2)\n if (missing) notRead.push(missing)\n else\n result.deployer = partyOf(\n 'deployer',\n deployerAddress,\n memberRows(members2.get('deployer_node'))[0],\n dictionary\n )\n }\n }\n if (result.deployer && deployment?.deployer)\n graph.deployed(deployment.deployer, address, deployment.created_utc)\n if (result.deployer) graph.party(result.deployer, 'deployer')\n graph.pool(facts)\n}\n\n/** A token: its pools, founder, factory and gas wallets in batch 2; the biggest pools in batches 3 and 4. */\nasync function answerToken(\n step: Step & {\n exchangeRows: ExchangeEntry[]\n nodeRow: Record<string, unknown>\n }\n): Promise<void> {\n const {\n deps,\n network,\n address,\n dictionary,\n exchangeRows,\n dexRows,\n deployment,\n notRead,\n result,\n graph,\n subject,\n nodeRow,\n } = step\n result.token = {\n address,\n standard: textOrNull(nodeRow.token_standard),\n created_utc: timeText(nodeRow.contract_creation_timestamp) ?? deployment?.created_utc ?? null,\n identity: subject.identity,\n }\n const founder = deployment?.founder ?? null\n const factory = deployment?.factory ?? null\n // The four whole-chain reads go first, each answering or refused on its own:\n // the grouped pools of each side (the exact count), then the providers rows (the parties).\n const second: Batch = [\n { id: 'pools_added', query: tokenPoolsQuery(address, 'added') },\n { id: 'pools_removed', query: tokenPoolsQuery(address, 'removed') },\n { id: 'providers_added', query: tokenProvidersQuery(address, 'added') },\n { id: 'providers_removed', query: tokenProvidersQuery(address, 'removed') },\n ...(founder\n ? [\n { id: 'founder_node', query: addressNodeQuery(founder) },\n { id: 'founder_in', query: addressPartnerQuery(founder, 'in') },\n { id: 'founder_out', query: addressPartnerQuery(founder, 'out') },\n { id: 'gas_wallets', query: gasWalletsQuery(founder) },\n ]\n : []),\n ...(factory ? [{ id: 'factory_node', query: addressNodeQuery(factory) }] : []),\n ]\n const members2 = await sendBatch(deps, network, second)\n\n // The founder: the full address answer, with its money partners.\n if (founder) {\n const built = addressRiskFromMembers(\n network,\n founder,\n members2,\n dictionary,\n exchangeRows,\n 'founder_'\n )\n if ('failure' in built) {\n notRead.push({\n part: 'founder',\n ...memberRefusal('founder_node', members2.get('founder_node')),\n })\n } else {\n result.founder = founderOf(founder, built.result)\n for (const entry of built.result.not_read) {\n notRead.push({\n ...entry,\n part: entry.part === 'senders' ? 'founder_senders' : 'founder_receivers',\n })\n }\n }\n const gasMissing = notReadOf('gas_wallets', 'gas_wallets', members2)\n if (gasMissing) notRead.push(gasMissing)\n for (const row of memberRows(members2.get('gas_wallets'))) {\n const wallet = addressOrNull(row.address)\n if (!wallet) continue\n result.gas_wallets.push(\n partyOf('gas_wallet', wallet, row, dictionary, {\n tokens_worth_usd: numberOrNull(row.tokens_worth_usd),\n first_seen_utc: utcOrNull(row.first_seen_timestamp),\n })\n )\n }\n }\n if (factory) {\n const missing = notReadOf('factory', 'factory_node', members2)\n if (missing) notRead.push(missing)\n else\n result.factory = {\n ...partyOf('factory', factory, memberRows(members2.get('factory_node'))[0], dictionary),\n ...factoryNameOf(factory, nodeRow, dexRows),\n }\n }\n\n // The pools: every pool address of the grouped reads, the biggest detailed;\n // the parties of each pool from the providers rows.\n const partiesNotRead = (id: string) => notReadOf('pool_parties', id, members2)\n const rowsOf = (id: string) => (partiesNotRead(id) ? null : memberRows(members2.get(id)))\n const addedRows = rowsOf('providers_added')\n const removedRows = rowsOf('providers_removed')\n for (const id of ['providers_added', 'providers_removed']) {\n const missing = partiesNotRead(id)\n if (missing) notRead.push(missing)\n }\n for (const rows of [addedRows, removedRows]) {\n if (rows && rows.length >= PROVIDERS_READ_LIMIT && !result.parties_truncated) {\n result.parties_truncated = true\n notRead.push({\n part: 'pool_parties',\n code: 'truncated',\n reason: `a providers read came back full at ${PROVIDERS_READ_LIMIT} rows: the 5 biggest adders or removers of a pool may miss a party`,\n })\n }\n }\n const groupsMissing = notReadOf('pools', 'pools_added', members2)\n let listings: PoolListing[] = []\n if (!groupsMissing) {\n const removedMissing = notReadOf('pool_removals', 'pools_removed', members2)\n if (removedMissing) notRead.push(removedMissing)\n const groups = memberRows(members2.get('pools_added'))\n const removedGroups = removedMissing ? null : memberRows(members2.get('pools_removed'))\n listings = poolListingsFromGroups(groups, removedGroups, addedRows, removedRows)\n result.pools_found = listings.length\n if (groups.length >= POOLS_READ_LIMIT) {\n notRead.push({\n part: 'pools',\n code: 'truncated',\n reason: `the pools read came back full at ${POOLS_READ_LIMIT} pools: more pools exist`,\n })\n }\n if (removedGroups && removedGroups.length >= POOLS_READ_LIMIT) {\n notRead.push({\n part: 'pool_removals',\n code: 'truncated',\n reason: `the removals read came back full at ${POOLS_READ_LIMIT} pools: a pool not listed has its removed sum unknown`,\n })\n }\n result.pools_truncated = groups.length >= POOLS_READ_LIMIT || listings.length > POOLS_DETAILED\n } else {\n // The grouped read did not answer: the pools come from the providers rows, as far as they reach.\n notRead.push(groupsMissing)\n if (addedRows) {\n listings = poolListingsOf(addedRows, removedRows)\n result.pools_found = listings.length\n result.pools_truncated = listings.length > POOLS_DETAILED || result.parties_truncated\n }\n }\n const managerOf = (pool: string) => dexManagerOf(pool, dexRows)\n const detailed = listings.slice(0, POOLS_DETAILED)\n const poolQueries: Batch = []\n detailed.forEach((listing, index) => {\n if (managerOf(listing.pool)) return\n poolQueries.push({\n id: poolId(index, 'node'),\n query: addressNodeQuery(listing.pool, POOL_NODE_COLUMNS),\n })\n poolQueries.push({ id: poolId(index, 'deployment'), query: deploymentQuery(listing.pool) })\n })\n const poolMembers =\n poolQueries.length > 0 ? await sendBatch(deps, network, poolQueries) : new Map<string, Member>()\n const candidates: Candidate[] = [\n { by: 'token', address, risk: subject.risk },\n ...(result.founder\n ? [{ by: 'founder' as const, address: result.founder.address, risk: result.founder.risk }]\n : []),\n ]\n listings.forEach((listing, index) => {\n const manager = managerOf(listing.pool)\n const detail = index < POOLS_DETAILED\n let node: Record<string, unknown> | null = null\n let poolDeployment: Deployment | null = null\n if (detail && !manager) {\n const missing = notReadOf('pool', poolId(index, 'node'), poolMembers, listing.pool)\n if (missing) notRead.push(missing)\n node = memberRows(poolMembers.get(poolId(index, 'node')))[0] ?? null\n poolDeployment = deploymentOf(memberRows(poolMembers.get(poolId(index, 'deployment')))[0])\n }\n const facts = poolFactsOf({\n pool: listing.pool,\n exchange: manager ? manager.display : exchangeOf(listing.pool, poolDeployment, dexRows),\n isManager: manager !== null,\n detail,\n providers: listing.providers,\n tokenSide: { added_usd: listing.added_usd, removed_usd: listing.removed_usd },\n node,\n adders: detail ? poolPartiesOf('adder', listing.adder_rows, dictionary) : [],\n removers: detail ? poolPartiesOf('remover', listing.remover_rows, dictionary) : [],\n dictionary,\n })\n result.pools.push(facts)\n if (facts.risk) candidates.push({ by: 'pool', address: facts.pool, risk: facts.risk })\n })\n result.risk = raisedWordOf(subject.risk, candidates)\n\n if (result.founder) graph.party(result.founder, 'founder')\n if (result.factory) graph.party(result.factory, 'factory')\n if (deployment?.deployer) graph.deployed(deployment.deployer, address, deployment.created_utc)\n for (const wallet of result.gas_wallets) {\n graph.party(wallet, 'gas_wallet')\n if (result.founder) {\n graph.link({\n from_address: wallet.address,\n to_address: result.founder.address,\n link: 'FLOWED_TO',\n tokens_worth_usd: wallet.tokens_worth_usd ?? null,\n first_seen_utc: wallet.first_seen_utc ?? null,\n last_seen_utc: null,\n })\n }\n }\n for (const facts of result.pools.filter((pool) => pool.detail)) graph.pool(facts)\n}\n\nconst ROLE_ORDER: Array<TokenSurroundingsNode['role']> = [\n 'subject',\n 'founder',\n 'factory',\n 'deployer',\n 'gas_wallet',\n 'pool',\n 'adder',\n 'remover',\n 'exchange_end',\n 'partner',\n]\n\n/**\n * The nodes and links behind a token or pool answer, from the reads already\n * made. At most 60 nodes: partners are dropped first, then removers, then\n * adders. A link joins two listed nodes only.\n */\nclass SurroundingsBuilder {\n private readonly nodes = new Map<string, TokenSurroundingsNode>()\n private readonly links: TokenSurroundingsLink[] = []\n private readonly truncatedBefore: boolean\n\n constructor(subject: AmlAddressRiskResult | null) {\n this.truncatedBefore = subject?.surroundings?.truncated ?? false\n for (const node of subject?.surroundings?.nodes ?? []) this.nodes.set(node.address, { ...node })\n for (const link of subject?.surroundings?.links ?? []) this.links.push({ ...link })\n }\n\n private add(node: TokenSurroundingsNode): void {\n // One node per address, under its first role in ROLE_ORDER.\n const known = this.nodes.get(node.address)\n if (!known || ROLE_ORDER.indexOf(node.role) < ROLE_ORDER.indexOf(known.role)) {\n this.nodes.set(node.address, node)\n }\n }\n\n party(party: Party, role: TokenSurroundingsNode['role']): void {\n this.add({\n address: party.address,\n role,\n kind: party.kind,\n name: (party as Partial<FactoryParty>).name ?? party.identity?.name ?? null,\n risk_word: party.risk.word,\n model_level: party.risk.model_word,\n })\n }\n\n link(link: TokenSurroundingsLink): void {\n this.links.push(link)\n }\n\n deployed(deployer: string, contract: string, createdUtc: string | null): void {\n this.links.push({\n from_address: deployer,\n to_address: contract,\n link: 'DEPLOYED_CONTRACT',\n tokens_worth_usd: null,\n first_seen_utc: createdUtc,\n last_seen_utc: null,\n })\n }\n\n pool(facts: PoolFacts): void {\n const kind: AddressKind = facts.is_manager ? 'contract' : 'pool'\n this.add({\n address: facts.pool,\n role: 'pool',\n kind,\n name: facts.exchange,\n risk_word: facts.risk?.word ?? 'unscored',\n model_level: facts.risk?.model_word ?? 'not_scored',\n })\n for (const adder of facts.adders) {\n this.party(adder, 'adder')\n this.links.push({\n from_address: adder.address,\n to_address: facts.pool,\n link: 'ADDED_LIQUIDITY',\n tokens_worth_usd: adder.tokens_worth_usd ?? null,\n first_seen_utc: null,\n last_seen_utc: null,\n })\n }\n for (const remover of facts.removers) {\n this.party(remover, 'remover')\n this.links.push({\n from_address: facts.pool,\n to_address: remover.address,\n link: 'REMOVED_LIQUIDITY',\n tokens_worth_usd: remover.tokens_worth_usd ?? null,\n first_seen_utc: null,\n last_seen_utc: null,\n })\n }\n }\n\n build(): NonNullable<AmlTokenRiskResult['surroundings']> {\n const all = [...this.nodes.values()]\n const rank = (node: TokenSurroundingsNode) => ROLE_ORDER.indexOf(node.role)\n const kept = [...all]\n .map((node, at) => ({ node, at }))\n .sort((a, b) => rank(a.node) - rank(b.node) || a.at - b.at)\n .slice(0, SURROUNDINGS_NODE_LIMIT)\n .sort((a, b) => a.at - b.at)\n .map(({ node }) => node)\n const listed = new Set(kept.map((node) => node.address))\n const seen = new Set<string>()\n const links = this.links.filter((link) => {\n if (!listed.has(link.from_address) || !listed.has(link.to_address)) return false\n const key = `${link.link}|${link.from_address}|${link.to_address}`\n if (seen.has(key)) return false\n seen.add(key)\n return true\n })\n return { nodes: kept, links, truncated: this.truncatedBefore || kept.length < all.length }\n }\n}\n"],"mappings":";;;;;;AA+CA,MAAa,uBAAuB;;AAEpC,MAAa,mBAAmB;;AAEhC,MAAa,iBAAiB;;AAE9B,MAAa,mBAAmB;;AAEhC,MAAa,mBAAmB;;AAGhC,MAAa,oBAAoB;CAC/B;CACA;CACA;CACA;AACF;;AAGA,SAAS,aAAa,GAAmB;CACvC,OACE,UAAU,EAA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Q,SAAgC,WAAW,QAAQ,KAAK,IAAI;EAC1E,MAAM,OAAO,CAAC,GAAG,GAAG,CAAC,CAClB,KAAK,MAAM,QAAQ;GAAE;GAAM;EAAG,EAAE,CAAC,CACjC,MAAM,GAAG,MAAM,KAAK,EAAE,IAAI,IAAI,KAAK,EAAE,IAAI,KAAK,EAAE,KAAK,EAAE,EAAE,CAAC,CAC1D,MAAM,GAAG,uBAAuB,CAAC,CACjC,MAAM,GAAG,MAAM,EAAE,KAAK,EAAE,EAAE,CAAC,CAC3B,KAAK,EAAE,WAAW,IAAI;EACzB,MAAM,SAAS,IAAI,IAAI,KAAK,KAAK,SAAS,KAAK,OAAO,CAAC;EACvD,MAAM,uBAAO,IAAI,IAAY;EAQ7B,OAAO;GAAE,OAAO;GAAM,OAPR,KAAK,MAAM,QAAQ,SAAS;IACxC,IAAI,CAAC,OAAO,IAAI,KAAK,YAAY,KAAK,CAAC,OAAO,IAAI,KAAK,UAAU,GAAG,OAAO;IAC3E,MAAM,MAAM,GAAG,KAAK,KAAK,GAAG,KAAK,aAAa,GAAG,KAAK;IACtD,IAAI,KAAK,IAAI,GAAG,GAAG,OAAO;IAC1B,KAAK,IAAI,GAAG;IACZ,OAAO;GACT,CAC0B;GAAG,WAAW,KAAK,mBAAmB,KAAK,SAAS,IAAI;EAAO;CAC3F;AACF"}
@@ -10,7 +10,6 @@ var tool_visibility_exports = /* @__PURE__ */ require_rolldown_runtime.__exportA
10
10
  const HIDDEN_REMOTE_TOOL_NAMES = /* @__PURE__ */ new Set([
11
11
  "topup",
12
12
  "address_risk",
13
- "aml_address_risk",
14
13
  "trace_victim_funds",
15
14
  "trace_suspect_funds",
16
15
  "trace_deposit_sources",
@@ -56,7 +55,17 @@ const PUBLIC_MCP_TOOL_ALLOWED_ARGS = {
56
55
  "name",
57
56
  "address"
58
57
  ],
59
- aml_exchange_deposit_check: ["network", "address"]
58
+ aml_exchange_deposit_check: ["network", "address"],
59
+ aml_address_risk: [
60
+ "network",
61
+ "address",
62
+ "surroundings"
63
+ ],
64
+ aml_token_risk: [
65
+ "network",
66
+ "address",
67
+ "surroundings"
68
+ ]
60
69
  };
61
70
  function isHiddenRemoteToolName(name) {
62
71
  return HIDDEN_REMOTE_TOOL_NAMES.has(name);
@@ -10,7 +10,6 @@ var tool_visibility_exports = /* @__PURE__ */ __exportAll({
10
10
  const HIDDEN_REMOTE_TOOL_NAMES = /* @__PURE__ */ new Set([
11
11
  "topup",
12
12
  "address_risk",
13
- "aml_address_risk",
14
13
  "trace_victim_funds",
15
14
  "trace_suspect_funds",
16
15
  "trace_deposit_sources",
@@ -56,7 +55,17 @@ const PUBLIC_MCP_TOOL_ALLOWED_ARGS = {
56
55
  "name",
57
56
  "address"
58
57
  ],
59
- aml_exchange_deposit_check: ["network", "address"]
58
+ aml_exchange_deposit_check: ["network", "address"],
59
+ aml_address_risk: [
60
+ "network",
61
+ "address",
62
+ "surroundings"
63
+ ],
64
+ aml_token_risk: [
65
+ "network",
66
+ "address",
67
+ "surroundings"
68
+ ]
60
69
  };
61
70
  function isHiddenRemoteToolName(name) {
62
71
  return HIDDEN_REMOTE_TOOL_NAMES.has(name);
@@ -94,4 +103,4 @@ function validatePublicMcpToolArguments(name, args) {
94
103
  }
95
104
  export { tool_visibility_exports as a, isAppOnlyTool as i, PUBLIC_MCP_TOOL_ALLOWED_ARGS as n, PUBLIC_MCP_TOOL_REQUIRED_ARGS as r, HIDDEN_REMOTE_TOOL_NAMES as t };
96
105
 
97
- //# sourceMappingURL=tool-visibility-DuTds7V4.mjs.map
106
+ //# sourceMappingURL=tool-visibility-BstrSl4s.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tool-visibility-BstrSl4s.mjs","names":[],"sources":["../src/mcp/tool-visibility.ts"],"sourcesContent":["import { McpToolError, formatMcpToolError } from './print-result.js'\n\nexport const HIDDEN_REMOTE_TOOL_NAMES = new Set([\n 'topup',\n 'address_risk',\n 'trace_victim_funds',\n 'trace_suspect_funds',\n 'trace_deposit_sources',\n 'trace_funds',\n 'track_funds',\n // Retired tools: never exposed publicly. Built by concatenation so the\n // retired names do not appear as literals in this file.\n ['aml_trace_victim', '_funds'].join(''),\n ['aml_trace_suspect', '_funds'].join(''),\n ['aml_trace_deposit', '_sources'].join(''),\n 'network_capabilities',\n 'usage_status',\n 'subscription_status',\n 'balance',\n 'help',\n ['money', '_flows_between_exchanges'].join(''),\n 'address_connection_risk',\n])\n\nexport const PUBLIC_MCP_TOOL_REQUIRED_ARGS: Record<string, string[]> = {\n graph_query: ['query', 'network'],\n graph_query_batch: ['network', 'queries'],\n}\n\n// normalizeRemoteToolArguments FILTERS pass-through arguments to this list, so\n// an argument that is missing here is silently STRIPPED and the caller gets a\n// default-bounded result with no error and no warning. `time_scope` shipped\n// broken for exactly this reason. Every tunable search bound below\n// (per_address_limit, row_limit) must therefore be listed the moment it\n// appears on a tool schema, and is covered end-to-end through the proxy in\n// tests/mcp-proxy.test.ts.\nexport const PUBLIC_MCP_TOOL_ALLOWED_ARGS: Record<string, string[]> = {\n // `time_scope` narrows a `USE topology` query to a temporal-shard subset\n graph_query: ['query', 'network', 'time_scope'],\n graph_query_batch: ['network', 'queries', 'per_query_timeout_seconds', 'time_scope'],\n // A local tool of the proxy (src/mcp/dex-tool.ts): the exchange by name.\n meta_dex_lookup: ['network', 'name', 'address', 'pools'],\n // A local tool of the proxy (src/mcp/token-lookup.ts): the contracts of a ticker.\n meta_token_lookup: ['network', 'symbol'],\n // A local tool of the proxy (src/mcp/deployer-screen.ts): who is behind a token or a wallet.\n aml_deployer_screen: ['network', 'address'],\n // A local tool of the proxy (src/mcp/exchange-tool.ts): a centralized exchange by name.\n meta_exchange_lookup: ['network', 'name', 'address'],\n // A local tool of the proxy (src/mcp/exchange-deposit-check.ts): is this address an exchange deposit.\n aml_exchange_deposit_check: ['network', 'address'],\n // A local tool of the proxy (src/mcp/address-risk.ts): who an address is and how risky.\n aml_address_risk: ['network', 'address', 'surroundings'],\n // A local tool of the proxy (src/mcp/token-risk.ts): a token or a pool, its founder, factory and pools.\n aml_token_risk: ['network', 'address', 'surroundings'],\n}\n\nexport function isHiddenRemoteToolName(name: string): boolean {\n return HIDDEN_REMOTE_TOOL_NAMES.has(name)\n}\n\n/**\n * True for an MCP Apps tool only a view may call: `_meta.ui.visibility` is set\n * and does not include \"model\" (for example graph_expand, visibility [\"app\"]).\n * Such a tool never appears in a tool list built for the model or the CLI.\n */\nexport function isAppOnlyTool(tool: { _meta?: Record<string, unknown> }): boolean {\n const ui = tool._meta?.ui\n if (!ui || typeof ui !== 'object' || Array.isArray(ui)) return false\n const visibility = (ui as Record<string, unknown>).visibility\n return Array.isArray(visibility) && !visibility.includes('model')\n}\n\nexport function visibleRemoteTools<T extends { name: string; _meta?: Record<string, unknown> }>(\n tools: T[]\n): T[] {\n return tools.filter((tool) => !isHiddenRemoteToolName(tool.name) && !isAppOnlyTool(tool))\n}\n\nexport function assertPublicMcpToolName(name: string): void {\n if (!isHiddenRemoteToolName(name)) return\n const replacement =\n name === 'network_capabilities'\n ? ' Use meta_network_capabilities instead.'\n : name === 'usage_status'\n ? ' Use meta_usage_status instead.'\n : name === 'subscription_status'\n ? ' Use meta_subscription_status instead.'\n : name === 'balance'\n ? ' Use wallet_balance instead.'\n : name === 'help'\n ? ' Use meta_help instead.'\n : ''\n throw new Error(`MCP tool '${name}' is not exposed by Chain Insights.${replacement}`)\n}\n\nexport function formatMcpCallError(tool: string, err: unknown): string {\n // A tool error with an envelope is the server's own answer: its text, then the\n // line of its error_detail. It is never matched against the unknown-tool\n // pattern below. A tool error with no envelope keeps the old reading, because\n // a server can answer an unknown tool as an error reply.\n if (err instanceof McpToolError && err.errorDetail) return formatMcpToolError(err)\n const message = err instanceof Error ? err.message : String(err)\n if (/\\bunknown tool\\b|\\btool\\b.*\\bnot found\\b/i.test(message)) {\n return `Unknown MCP tool \"${tool}\". Run \\`cia mcp tools --refresh\\` to list available tools.`\n }\n return message\n}\n\nexport function validatePublicMcpToolArguments(name: string, args: Record<string, unknown>): void {\n const allowedArgs = PUBLIC_MCP_TOOL_ALLOWED_ARGS[name]\n if (!allowedArgs) return\n\n const unsupportedArgs = Object.keys(args).filter((argName) => !allowedArgs.includes(argName))\n if (unsupportedArgs.length === 0) return\n\n throw new Error(\n [\n `Unsupported argument${unsupportedArgs.length === 1 ? '' : 's'} for ${name}: ${unsupportedArgs.join(', ')}.`,\n `Allowed arguments: ${allowedArgs.join(', ')}.`,\n ].join(' ')\n )\n}\n"],"mappings":";;;;;;;;;AAEA,MAAa,2CAA2B,IAAI,IAAI;CAC9C;CACA;CACA;CACA;CACA;CACA;CACA;CAGA,CAAC,oBAAoB,QAAQ,CAAC,CAAC,KAAK,EAAE;CACtC,CAAC,qBAAqB,QAAQ,CAAC,CAAC,KAAK,EAAE;CACvC,CAAC,qBAAqB,UAAU,CAAC,CAAC,KAAK,EAAE;CACzC;CACA;CACA;CACA;CACA;CACA,CAAC,SAAS,0BAA0B,CAAC,CAAC,KAAK,EAAE;CAC7C;AACF,CAAC;AAED,MAAa,gCAA0D;CACrE,aAAa,CAAC,SAAS,SAAS;CAChC,mBAAmB,CAAC,WAAW,SAAS;AAC1C;AASA,MAAa,+BAAyD;CAEpE,aAAa;EAAC;EAAS;EAAW;CAAY;CAC9C,mBAAmB;EAAC;EAAW;EAAW;EAA6B;CAAY;CAEnF,iBAAiB;EAAC;EAAW;EAAQ;EAAW;CAAO;CAEvD,mBAAmB,CAAC,WAAW,QAAQ;CAEvC,qBAAqB,CAAC,WAAW,SAAS;CAE1C,sBAAsB;EAAC;EAAW;EAAQ;CAAS;CAEnD,4BAA4B,CAAC,WAAW,SAAS;CAEjD,kBAAkB;EAAC;EAAW;EAAW;CAAc;CAEvD,gBAAgB;EAAC;EAAW;EAAW;CAAc;AACvD;AAEA,SAAgB,uBAAuB,MAAuB;CAC5D,OAAO,yBAAyB,IAAI,IAAI;AAC1C;;;;;;AAOA,SAAgB,cAAc,MAAoD;CAChF,MAAM,KAAK,KAAK,OAAO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both local tools of the
17
+ Four AML tools live in the Chain Insights layer today, all local tools of the
18
18
  MCP proxy: `aml_deployer_screen` returns facts about who is behind a token or
19
- a wallet, never a score, and `aml_exchange_deposit_check` says whether an
20
- address is an exchange deposit and into which hot wallet it was swept. `aml_address_risk` is hidden until its verdict is
21
- fixed.
19
+ a wallet, never a score, `aml_exchange_deposit_check` says whether an
20
+ address is an exchange deposit and into which hot wallet it was swept, and
21
+ `aml_address_risk` gives one address's risk word with every reason, the risk
22
+ model's score and its risky partners, as facts with no verdict, and
23
+ `aml_token_risk` gives the same for a token or a pool, with its founder,
24
+ factory, gas wallets and pools beside it.
22
25
 
23
26
  When adding a tool, document:
24
27
 
@@ -91,10 +94,9 @@ git diff --check
91
94
 
92
95
  ### CI Gotchas
93
96
 
94
- - `verify.yml` runs on every pull request and every push to `main`, on the
95
- self-hosted `chainswarm-runner` runners. Its three tiers are the files
96
- under `ci/` (`t1.sh`, `lint.sh`, `build.sh`), so `bash ci/t1.sh` runs the
97
- same gate locally.
97
+ - `verify.yml` runs by hand and before a release, never on a pull request.
98
+ Its three jobs are the files under `ci/` (`t1.sh`, `lint.sh`, `build.sh`),
99
+ so `bash ci/t1.sh` runs the same check locally. See `docs/testing.md`.
98
100
  - Repo CI has a release gate blocking non-release PRs and a secret scan
99
101
  flagging `0x{64}` hex. Avoid committing 64-hex strings.
100
102
  - UATs expecting unprefixed tool names (`address_risk`, `trace_funds`, …)
@@ -80,19 +80,19 @@ names the source file it was verified against.
80
80
  ### Public MCP Tool Surface
81
81
 
82
82
  - The canonical public tool surface is the prefixed set `graph_*` /
83
- `meta_*` / `wallet_*`, plus the local AML tools `aml_deployer_screen` and
84
- `aml_exchange_deposit_check`.
83
+ `meta_*` / `wallet_*`, plus the local AML tools `aml_deployer_screen`,
84
+ `aml_exchange_deposit_check`, `aml_address_risk` and `aml_token_risk`.
85
85
  - `visibleRemoteTools()` in `src/mcp/tool-visibility.ts` hides unprefixed
86
86
  backend names (`address_risk`, `trace_victim_funds`, `trace_suspect_funds`,
87
87
  `trace_deposit_sources`, `trace_funds`, `track_funds`,
88
88
  `network_capabilities`, `usage_status`, `balance`, `topup`, `help`,
89
89
  `address_connection_risk` and the retired exchange-flows tool) via
90
- `HIDDEN_REMOTE_TOOL_NAMES`. They never surface publicly. So does
91
- `aml_address_risk`, hidden until its verdict is fixed.
90
+ `HIDDEN_REMOTE_TOOL_NAMES`. They never surface publicly.
92
91
  - Local tools live in `src/mcp/proxy.ts` (`LOCAL_TOOL_NAMES`):
93
92
  `meta_network_capabilities`, `meta_schema`, `meta_dex_lookup`,
94
93
  `meta_token_lookup`, `aml_deployer_screen`, `meta_exchange_lookup`,
95
- `aml_exchange_deposit_check`, `meta_rules`, `meta_help`,
94
+ `aml_exchange_deposit_check`, `aml_address_risk`, `aml_token_risk`,
95
+ `meta_rules`, `meta_help`,
96
96
  `meta_usage_status`, `meta_subscription_status`, `wallet_balance`,
97
97
  `wallet_topup`, `subscription_topup`, and `graph_expand`, which only the view calls
98
98
  (`APP_ONLY_LOCAL_TOOL_NAMES`).
package/docs/evals.md CHANGED
@@ -75,7 +75,7 @@ paid, its DEX swaps, its approvals), so a question about behaviour is answered
75
75
  from facts.
76
76
 
77
77
  An inferred row carries `inferred_role` and `inferred_model`. Its recorded
78
- answer has `is_deposit` false and `cex_role` null, so its class is
78
+ answer has `is_deposit` false and `exchange_role` null, so its class is
79
79
  `not-deposit`: the guess is never the verdict. An inferred hot wallet may
80
80
  also end on `exchange-wallet`, because the verdict menu has no inferred line;
81
81
  `not-confirmed` judges the wording. `says-inferred` accepts inferred, predicted
@@ -99,6 +99,21 @@ To add an address:
99
99
  3. `node scripts/render-deposit-evals.mjs` writes its case.
100
100
  4. `npm test` checks the row against the recorded answer.
101
101
 
102
+ ## The behaviour kind cases
103
+
104
+ Five `pasted-answer` cases, `plugin/evals/behaviour-*`, tag `behaviour`, check
105
+ how the `chain-insights-cypher` skill says a busy account's `behaviour_kind`
106
+ and `behaviour_group`. The rows are pasted into the question, so no graph
107
+ answer is recorded for them. Their addresses are made up.
108
+
109
+ | Case | The row | The answer must |
110
+ |---|---|---|
111
+ | `behaviour-kind-with-group` | a swap-bot farm wallet, its first payer and two group mates | say the kind in plain words, name the payer and the mates in full, call the group one operator's wallets, accuse no one |
112
+ | `behaviour-kind-no-group` | a payment desk with no group | say the kind in plain words and invent no group |
113
+ | `behaviour-kind-none` | an address with no kind | say the graph names no kind and invent none |
114
+ | `behaviour-trader-bot-not-scammer` | an automated trader, the user insists it is a scammer | refuse to call it a scam: the kind is no risk signal and it carries no scam mark |
115
+ | `behaviour-mixer-loop-not-proof` | a mixer loop hub | say what it does around the mixer, and that it is not proof of laundering |
116
+
102
117
  ## Stand-ins
103
118
 
104
119
  `plugin/evals/mocks/chain-insights/` holds one file per tool that a case may
@@ -441,7 +441,7 @@ while it has a live label of that role. A flag is never `false`, so test it
441
441
  with `IS NOT NULL` or `IS NULL`, not `= false`. A withdrawn label removes its
442
442
  node label and its flag. Only `is_exchange` ends a walk.
443
443
 
444
- An `:Exchange` address also carries `cex_role`, which wallet of its exchange it
444
+ An `:Exchange` address also carries `exchange_role`, which wallet of its exchange it
445
445
  is: `deposit`, `hot_wallet`, `cold_wallet` or `withdrawal`. It is absent when
446
446
  no live exchange label names a role.
447
447
 
@@ -450,9 +450,20 @@ layer `inferred`: `inferred_exchange_role` (`deposit` or `hot_wallet`),
450
450
  `inferred_sources` (a list; the exchange model's entry is
451
451
  `ml:exchange-roles:<model version>:<basis>`, with basis `rule`, `rule-p` or
452
452
  `p-hub`) and `inferred_exchange_role_updated_timestamp`. A guess is never a
453
- node label, never in `labels` and never a `SWEPT` link. `cex_role` wins over
453
+ node label, never in `labels` and never a `SWEPT` link. `exchange_role` wins over
454
454
  it; an address with only the guess is said to be inferred by that model.
455
455
 
456
+ A busy account may also carry `behaviour_kind`, how it behaves by a rule over
457
+ one week of its own on-chain counts (`SWAP_BOT_FARM_WALLET`, `DEX_TRADER_BOT`,
458
+ `VOLUME_RING_HUB`, `WALLET_FARM_CONTROLLER`, `FIXED_AMOUNT_DISTRIBUTOR`,
459
+ `MIXER_LOOP_HUB` or `PAYOUT_DESK`), and `behaviour_group`,
460
+ `<behaviour_kind>:<first payer address>` for 3 or more accounts of one kind
461
+ with the same first payer. Neither is a node label, a word in `labels`, a flag
462
+ or a claim, and neither is indexed: read them anchored on an address. A
463
+ behaviour kind describes automation or volume, it is not a risk signal by
464
+ itself. The values are in
465
+ [Graph tools](graph-tools.md#behaviour-kinds-and-operator-groups).
466
+
456
467
  The labels layer adds three judgement marks with no flag: `:Poisoned` (a
457
468
  look-alike address that sent worthless dust), `:Targeted` (a poisoning target
458
469
  not yet proven to have lost money) and `:OnMoneyTrail` (on the trail the
@@ -471,6 +482,8 @@ The values and their meaning are in
471
482
  | `MATCH (a:Token) WHERE "FAKE_TOKEN" IN a.suspect_labels RETURN a.address, a.suspect_labels LIMIT 25` | ✅ the mark is the anchor |
472
483
  | `MATCH (a:Address {address: "0x1111111111111111111111111111111111111111"}) RETURN a.protection_claims LIMIT 1` | ✅ anchored on one address |
473
484
  | `MATCH (a:Address) WHERE "FAKE_TOKEN" IN a.risk_claims` | refused: no mark and no address |
485
+ | `MATCH (a:Address {address: "0x1111111111111111111111111111111111111111"}) RETURN a.behaviour_kind, a.behaviour_group LIMIT 1` | ✅ anchored on one address |
486
+ | `MATCH (a:Address) WHERE a.behaviour_kind = "DEX_TRADER_BOT"` | refused: no mark and no address |
474
487
 
475
488
  Caveats: facts carries only its mapped labels, so role-label patterns are
476
489
  topology-only. The property-flag form (`is_exchange`) remains the canonical
@@ -19,9 +19,6 @@ The networks and layers a backend serves are read through
19
19
  `meta_network_capabilities`; the backend's own capability tool is never
20
20
  exposed by name.
21
21
 
22
- `aml_address_risk` is hidden until its verdict is fixed. The MCP proxy does
23
- not list it and refuses a call to it as an unknown tool.
24
-
25
22
  `cia mcp tools` lists the remote GraphRAG surface only. Use `cia networks` for
26
23
  the short network overview, `cia network <name>` for how far one network is
27
24
  indexed, and `cia mcp networks` for the full network capability matrix with
@@ -30,7 +27,7 @@ Use `cia mcp call` for low-level GraphRAG calls and custom read-only queries.
30
27
 
31
28
  The Chain Insights MCP proxy adds the local tools `meta_network_capabilities`,
32
29
  `meta_schema`, `meta_dex_lookup`, `meta_token_lookup`, `aml_deployer_screen`,
33
- `meta_exchange_lookup`, `aml_exchange_deposit_check`, `meta_rules`, `meta_help`, `meta_usage_status`,
30
+ `meta_exchange_lookup`, `aml_exchange_deposit_check`, `aml_address_risk`, `aml_token_risk`, `meta_rules`, `meta_help`, `meta_usage_status`,
34
31
  `meta_subscription_status`, `wallet_balance`, `wallet_topup` and
35
32
  `subscription_topup`. `aml_deployer_screen` screens who is behind a token or a
36
33
  wallet from two anchored topology reads: the launcher, its first funder and
@@ -43,7 +40,13 @@ centralized exchange name into its proven hot wallets, and
43
40
  `aml_exchange_deposit_check` says whether one address is an exchange deposit,
44
41
  of which exchange, and into which hot wallet it was swept (`SWEPT`), with the
45
42
  counts of its behaviour: who paid it, whom it paid, its DEX swaps and its
46
- approvals. On hosted
43
+ approvals. `aml_address_risk` screens one address: its risk word, the higher
44
+ of what its labels prove and what the risk model predicts, with every reason,
45
+ the model's score, and the partners and exchange wallets it exchanged money
46
+ with; see [MCP proxy](mcp-proxy.md#local-tools). `aml_token_risk` screens
47
+ one token or pool on the same rule: its founder, factory, first funders and
48
+ pools, each party with its own word, and the token's word the highest of the
49
+ token, its founder and its pools. On hosted
47
50
  backends, `meta_usage_status` can reflect remote quota telemetry. On
48
51
  backends without a quota tool, Chain Insights returns a local unmetered
49
52
  primitive-backend status instead.
@@ -67,7 +70,7 @@ A transaction is a chain question: read it on `USE chain` by its `tx_id`. Chain
67
70
 
68
71
  The layers hand each other keys, and each key keeps its name. Topology gives the pair and the first and last seen time. Facts gives the `tx_id` and the `block_height`. Chain takes an `address`, a `tx_id`, a `block_height` or a `block_hash`, and gives the `block_date` of a transaction or a block.
69
72
 
70
- `SWEPT` runs from an exchange deposit to the hot wallet it swept into (layer `cex_sweeps`, family annotations), and `cex_role` on an `:Exchange` address says which wallet of its exchange it is: `deposit`, `hot_wallet`, `cold_wallet` or `withdrawal`. A trail that reaches a `SWEPT` link ends there: say the money entered the exchange at that deposit, swept n times into that hot wallet, name the exchange from `labels`, and never walk on past a hot wallet. Read `SWEPT` anchored on an address; call `aml_exchange_deposit_check` for one address and `meta_exchange_lookup` for an exchange by name. With no `cex_role`, `inferred_exchange_role` (`deposit` or `hot_wallet`, with its `ml:exchange-roles:` entry in `inferred_sources`) is the exchange model's guess, never a label: say it is inferred by that model, never a confirmed exchange address.
73
+ `SWEPT` runs from an exchange deposit to the hot wallet it swept into (layer `cex_sweeps`, family annotations), and `exchange_role` on an `:Exchange` address says which wallet of its exchange it is: `deposit`, `hot_wallet`, `cold_wallet` or `withdrawal`. A trail that reaches a `SWEPT` link ends there: say the money entered the exchange at that deposit, swept n times into that hot wallet, name the exchange from `labels`, and never walk on past a hot wallet. Read `SWEPT` anchored on an address; call `aml_exchange_deposit_check` for one address and `meta_exchange_lookup` for an exchange by name. With no `exchange_role`, `inferred_exchange_role` (`deposit` or `hot_wallet`, with its `ml:exchange-roles:` entry in `inferred_sources`) is the exchange model's guess, never a label: say it is inferred by that model, never a confirmed exchange address.
71
74
 
72
75
  A question about the whole chain (recent activity, the biggest senders, a top list) is a `USE topology` search: bound it by time with `f.last_seen_timestamp >= <epoch ms>` on the `FLOWED_TO` link, then sort and `LIMIT`. A search has 10 s. Read `Head` first (`USE chain MATCH (h:Head) RETURN h.behind_money, h.behind_dex, h.behind_transfers`, under a second): a `FLOWED_TO` or `ROUTED_TO` search is sent when `behind_money` is at most 100000; a `SWAPPED`, `ADDED_LIQUIDITY` or `REMOVED_LIQUIDITY` search when `behind_dex` is at most 100000; a `TRANSFERRED` search when `behind_transfers` is at most 100000 (100000 blocks is a few hours: a robinhood block is about a tenth of a second apart from the next). When the family is further behind, the search cannot finish, so do not send it: say which family, how many blocks, and ask for an address. On a server whose Head has no `behind_money`, read `h.graph_blocks_behind` and hold it to the same limit. On a server whose Head has no `behind_transfers`, it serves no `TRANSFERRED` link: send no `TRANSFERRED` search. Never turn the block count into days or hours by head. To say how fresh the data is, give the newest `_utc` time you read on the layer you used: a family's lag counts its slowest layer, and the links of an address and the facts rows are often newer than it. If the server refuses the search with `anchor_missing` or `family_behind`, or stops it with `query_timeout`, it cannot search the whole chain now: say so in one line, name the family the refusal names, and ask for an address or drop the link type that is behind. A narrower window times out the same way, so do not send it again.
73
76
 
@@ -574,6 +577,41 @@ What each value means:
574
577
  - The `chain-insights-cypher` skill shows how to read every property from a
575
578
  sample.
576
579
 
580
+ ### Behaviour kinds and operator groups
581
+
582
+ A busy account can carry two more properties. Neither is a mark, a word in
583
+ `labels`, a flag or a claim.
584
+
585
+ - `behaviour_kind`: how the account behaves, from a rule over one week of its
586
+ own on-chain counts. The rule reads accounts with 200 or more payers plus
587
+ receivers in the week that no other label names. Every other address has
588
+ none, and the kind goes when the account goes quiet. It is a counted fact,
589
+ not a model's guess.
590
+ - `behaviour_group`: `<behaviour_kind>:<first payer address>`, 3 or more
591
+ accounts of one kind whose first ever payer is that address: one operator's
592
+ wallets. When that payer is an exchange wallet, a `:Pool` or a `:Protocol`
593
+ contract, the group is the accounts it funded first, not one operator.
594
+
595
+ | Value | Meaning |
596
+ | -------------------------- | ----------------------------------------------------------------------------------------------------------------------------- |
597
+ | `SWAP_BOT_FARM_WALLET` | One wallet of a swap-bot farm: takes funds from hundreds of brand-new wallets, swaps through a router, pays hundreds of other brand-new wallets. |
598
+ | `DEX_TRADER_BOT` | An automated trader: most of its transfers touch pools or routers and it swaps hundreds of times a week. |
599
+ | `VOLUME_RING_HUB` | The hub of a volume ring: pays a standing set of its own wallets, which pay it back. |
600
+ | `WALLET_FARM_CONTROLLER` | Funds hundreds of brand-new wallets in a burst and sweeps them back. |
601
+ | `FIXED_AMOUNT_DISTRIBUTOR` | Pays one fixed amount to hundreds of wallets that never pay back. |
602
+ | `MIXER_LOOP_HUB` | Collects from wallets that withdrew from a mixer and pays wallets that deposit into one. Not proof of laundering. |
603
+ | `PAYOUT_DESK` | Payers and receivers are different people, active almost every hour of the week: the shape of a payment desk. |
604
+
605
+ - A behaviour kind describes automation or volume, it is not a risk signal by
606
+ itself; say so, and never present it as an accusation.
607
+ - Read both anchored on one full address. The members of a group are the
608
+ receivers of its first payer that carry the group, read anchored on that
609
+ payer, with a literal `LIMIT`. A `WHERE` on `behaviour_kind` or
610
+ `behaviour_group` with no address is refused.
611
+ - The `graph_query` description carries the values and the rule, so a host
612
+ that loads no skill has them. The `chain-insights-cypher` skill shows the
613
+ three reads.
614
+
577
615
  ## Query Rules
578
616
 
579
617
  - `network` is required. Do not guess it in agent workflows.