chain-insights 0.44.0 → 0.45.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 (33) hide show
  1. package/README.md +8 -6
  2. package/bin/install.cjs +2 -4
  3. package/dist/cache-location-BO2XkfgI.mjs +11 -0
  4. package/dist/cache-location-BO2XkfgI.mjs.map +1 -0
  5. package/dist/cache-location-CBVzUIxq.cjs +23 -0
  6. package/dist/{capabilities-A8fsfP24.cjs → capabilities-BGkL9yAr.cjs} +6 -0
  7. package/dist/{capabilities-DfWL6n_g.mjs → capabilities-Cur8x6c7.mjs} +2 -2
  8. package/dist/{capabilities-DfWL6n_g.mjs.map → capabilities-Cur8x6c7.mjs.map} +1 -1
  9. package/dist/cli.cjs +32 -6
  10. package/dist/cli.mjs +32 -6
  11. package/dist/cli.mjs.map +1 -1
  12. package/dist/graph-schema-D1orCe5F.mjs +914 -0
  13. package/dist/graph-schema-D1orCe5F.mjs.map +1 -0
  14. package/dist/graph-schema-znb_9MYq.cjs +972 -0
  15. package/dist/mcp-proxy.cjs +43 -462
  16. package/dist/mcp-proxy.d.cts.map +1 -1
  17. package/dist/mcp-proxy.d.mts.map +1 -1
  18. package/dist/mcp-proxy.mjs +35 -454
  19. package/dist/mcp-proxy.mjs.map +1 -1
  20. package/dist/public-tools-CZyeptJQ.mjs.map +1 -1
  21. package/dist/{schema-cache-DJdU4MIP.mjs → schema-cache-BT-kHy_r.mjs} +4 -5
  22. package/dist/schema-cache-BT-kHy_r.mjs.map +1 -0
  23. package/dist/{schema-cache-n7Gbhvsj.cjs → schema-cache-DwddPLcY.cjs} +3 -5
  24. package/docs/architecture.md +2 -0
  25. package/docs/graph-query-compatibility.md +4 -5
  26. package/docs/graph-tools.md +22 -14
  27. package/docs/mcp-proxy.md +17 -5
  28. package/docs/stability.md +2 -1
  29. package/package.json +1 -1
  30. package/skills/chain-insights-cypher/SKILL.md +137 -67
  31. package/skills/chain-insights-cypher/agents/openai.yaml +1 -1
  32. package/dist/schema-cache-DJdU4MIP.mjs.map +0 -1
  33. package/skills/chain-insights-schema-evm/SKILL.md +0 -541
@@ -5,7 +5,8 @@ const require_client = require("./client-Ypw9BNbn.cjs");
5
5
  const require_tool_visibility = require("./tool-visibility-CDe-ft0L.cjs");
6
6
  const require_usage_status = require("./usage-status-BdwwgYsu.cjs");
7
7
  const require_subscription_status = require("./subscription-status-Cm7LqY_h.cjs");
8
- const require_capabilities = require("./capabilities-A8fsfP24.cjs");
8
+ const require_capabilities = require("./capabilities-BGkL9yAr.cjs");
9
+ const require_graph_schema = require("./graph-schema-znb_9MYq.cjs");
9
10
  const require_action_log = require("./action-log-HniMMF7f.cjs");
10
11
  let node_url = require("node:url");
11
12
  let node_path = require("node:path");
@@ -74,469 +75,18 @@ function routingHintLines() {
74
75
  return [`- Pick the layer first. ${ROUTING_RULE} 1. ${ROUTING_LINES[0]} 2. ${ROUTING_LINES[1]} 3. ${ROUTING_LINES[2]} ${ROUTING_NO_ADDRESS_ON_CHAIN} ${ROUTING_TWO_FIT} ${ROUTING_HANDOFF} ${ROUTING_NOT_SERVED} The lookups that USE chain serves are listed in chain_admission.lookups of meta_network_capabilities. Read every limit that the server publishes from meta_network_capabilities (chain_admission and, when the server sends them, topology_admission and facts_admission). Never write a limit down.`, `- Act on a refusal by its class. ${moveLines().join(" ")}`];
75
76
  }
76
77
  //#endregion
77
- //#region src/mcp/flows.ts
78
- /**
79
- * graph_expand, the one dedicated tool of the local proxy, called by the Chain
80
- * Insights view (ui://chain-insights/view) when the investigator clicks. Its
81
- * _meta says visibility ["app"], so a host keeps it away from the model: the
82
- * model writes its own graph_query, and the view draws the rows by their column
83
- * names.
84
- *
85
- * Two forms, told apart by the arguments:
86
- *
87
- * - node, {network, address, in_offset?, out_offset?}: one address with its
88
- * newest senders and receivers, a text summary and chain-insights.flows.v1 in
89
- * structuredContent. Composed from three anchored graph_query reads on the
90
- * topology graph (the node, its outgoing FLOWS_TO and its incoming FLOWS_TO,
91
- * newest first).
92
- * - link, {network, from, to, day}: the transfers between two known addresses
93
- * on one UTC day, newest first, at most 50, a short text summary and
94
- * chain-insights.transfers.v1 in structuredContent. One anchored USE facts
95
- * graph_query read.
96
- *
97
- * Every read goes through the proxy's remote client, the same path and payment
98
- * wrapping a graph_query call takes, and is billed as a graph_query. Every
99
- * argument is checked before the first read, so a refused call reaches no graph
100
- * endpoint and costs nothing.
101
- */
102
- const FLOWS_SCHEMA = "chain-insights.flows.v1";
103
- const GRAPH_EXPAND_TOOL = "graph_expand";
104
- const FLOWS_NETWORK = "robinhood";
105
- /** Where a graph_expand page may start on each side, at most. */
106
- const FLOWS_MAX_OFFSET = 1e4;
107
- const TRANSFERS_SCHEMA = "chain-insights.transfers.v1";
108
- const INVALID_ADDRESS_TEXT = "invalid_address: a full 0x address of 40 hexadecimal characters is needed, for example 0x04911a118f11c75667e4d0dfb8e640af5a353550";
109
- const OFFSET_TOO_LARGE_TEXT = `invalid_offset: in_offset and out_offset must each be at most ${FLOWS_MAX_OFFSET}`;
110
- const OFFSET_NEGATIVE_TEXT = "invalid_offset: in_offset and out_offset must each be a whole number, 0 or more";
111
- const BOTH_FORMS_TEXT = "invalid_arguments: pass address (with in_offset and out_offset) to expand a node, or from, to and day to list the transfers of a link, not both";
112
- const ADDRESS_PATTERN = /^0x[0-9a-f]{40}$/;
113
- const DAY_PATTERN = /^\d{4}-\d{2}-\d{2}$/;
114
- const CODE_PREFIX = /^([a-z][a-z0-9_]*):\s*/;
115
- /**
116
- * The address lower-cased, or null when it is not 0x and 40 hexadecimal
117
- * characters. Only an address that passes is ever written into a read, so the
118
- * reads can carry it as a literal.
119
- */
120
- function normalizeFlowsAddress(raw) {
121
- if (typeof raw !== "string") return null;
122
- const address = raw.trim().toLowerCase();
123
- return ADDRESS_PATTERN.test(address) ? address : null;
124
- }
125
- /**
126
- * The day as YYYY-MM-DD when it is a real calendar date, or null. Only a day
127
- * that passes is ever written into a read.
128
- */
129
- function normalizeFlowsDay(raw) {
130
- if (typeof raw !== "string") return null;
131
- const day = raw.trim();
132
- if (!DAY_PATTERN.test(day)) return null;
133
- const time = Date.parse(`${day}T00:00:00Z`);
134
- if (Number.isNaN(time) || new Date(time).toISOString().slice(0, 10) !== day) return null;
135
- return day;
136
- }
137
- /**
138
- * The one facts read of a link: the transfers from one address to another on
139
- * one day. A facts read names the pair with one day, takes no ORDER BY and
140
- * holds at most 200 rows, so the read asks for the whole cap and the order is
141
- * made in buildTransfersView. Both addresses and the day have passed their
142
- * checks, so they are written into the read as literals.
143
- */
144
- function transfersReadFor(from, to, day) {
145
- return `USE facts MATCH (a:Address {address: "${from}"})-[t:TRANSFER]->(b:Address {address: "${to}"}) WHERE t.block_date = "${day}" RETURN t.tx_id AS tx_id, t.block_timestamp AS block_timestamp, t.amount AS amount, t.asset_symbol AS asset_symbol, t.amount_usd AS amount_usd LIMIT 200`;
146
- }
147
- const NODE_FIELDS = "b.address AS address, b.labels AS labels, b.is_exchange AS is_exchange, b.is_sanctioned AS is_sanctioned, b.is_scam AS is_scam, b.is_victim AS is_victim, b:Pool AS pool, b.total_in_usd AS total_in_usd, b.total_out_usd AS total_out_usd, b.degree_in AS degree_in, b.degree_out AS degree_out";
148
- const PARTY_FIELDS = NODE_FIELDS + ", f.amount_usd_sum AS usd, f.tx_count AS tx_count, " + "f.first_seen_timestamp AS first_seen, f.last_seen_timestamp AS last_seen";
149
- const PAGE_ORDER = " ORDER BY f.last_seen_timestamp DESC, b.address";
150
- /**
151
- * The three anchored reads of one page. Each side asks for one row more than
152
- * it shows: the extra row says another page exists.
153
- */
154
- function flowsReadsFor(address, inOffset, outOffset) {
155
- const page = (offset) => `${PAGE_ORDER}${offset > 0 ? ` SKIP ${offset}` : ""} LIMIT 13`;
156
- return [
157
- {
158
- id: "node",
159
- query: `USE topology MATCH (b:Address {address: '${address}'}) RETURN ${NODE_FIELDS} LIMIT 1`
160
- },
161
- {
162
- id: "out",
163
- query: `USE topology MATCH (a:Address {address: '${address}'})-[f:FLOWS_TO]->(b:Address) RETURN ${PARTY_FIELDS}${page(outOffset)}`
164
- },
165
- {
166
- id: "in",
167
- query: `USE topology MATCH (b:Address)-[f:FLOWS_TO]->(a:Address {address: '${address}'}) RETURN ${PARTY_FIELDS}${page(inOffset)}`
168
- }
169
- ];
170
- }
171
- /** The role word of an address, first match wins. */
172
- function flowsRole(row) {
173
- if (row.is_exchange === true) return "exchange";
174
- if (row.is_sanctioned === true) return "sanctioned";
175
- if (row.is_scam === true) return "scam";
176
- if (row.is_victim === true) return "victim";
177
- if (row.pool === true) return "pool";
178
- return "other";
179
- }
180
- function flowsFloat(value) {
181
- return typeof value === "number" && Number.isFinite(value) ? value : 0;
182
- }
183
- function flowsInt(value) {
184
- return typeof value === "number" && Number.isFinite(value) ? Math.trunc(value) : 0;
185
- }
186
- function flowsNodeOf(row) {
187
- const labels = Array.isArray(row.labels) ? row.labels.filter((label) => typeof label === "string") : [];
188
- return {
189
- address: typeof row.address === "string" ? row.address : "",
190
- role: flowsRole(row),
191
- labels,
192
- total_in_usd: flowsFloat(row.total_in_usd),
193
- total_out_usd: flowsFloat(row.total_out_usd),
194
- degree_in: flowsInt(row.degree_in),
195
- degree_out: flowsInt(row.degree_out)
196
- };
197
- }
198
- function assembleFlowView(network, page, senders, receivers, truncated) {
199
- const center = flowsNodeOf(page.center);
200
- const view = {
201
- schema: FLOWS_SCHEMA,
202
- network,
203
- center: center.address,
204
- nodes: [center],
205
- edges: [],
206
- cursor: {
207
- in_offset: page.inOffset + senders.length,
208
- out_offset: page.outOffset + receivers.length
209
- },
210
- truncated
211
- };
212
- const seen = /* @__PURE__ */ new Set([center.address]);
213
- const add = (row, incoming) => {
214
- const node = flowsNodeOf(row);
215
- if (!seen.has(node.address)) {
216
- seen.add(node.address);
217
- view.nodes.push(node);
218
- }
219
- view.edges.push({
220
- from: incoming ? node.address : center.address,
221
- to: incoming ? center.address : node.address,
222
- usd: flowsFloat(row.usd),
223
- tx_count: flowsInt(row.tx_count),
224
- first_seen_ms: flowsInt(row.first_seen),
225
- last_seen_ms: flowsInt(row.last_seen)
226
- });
227
- };
228
- for (const row of senders) add(row, true);
229
- for (const row of receivers) add(row, false);
230
- return view;
231
- }
232
- function fitsFlowBudget(view) {
233
- return view.nodes.length <= 60 && JSON.stringify(view).length < 4e4;
234
- }
235
- /**
236
- * flows.v1 from one page: the centre first, then the senders and the
237
- * receivers, each newest first, at most FLOWS_PER_SIDE a side. When the view
238
- * data would hold more than FLOWS_MAX_NODES addresses or reach FLOWS_MAX_CHARS
239
- * characters, the oldest links go first, the view is marked truncated, and the
240
- * cursor still says where the next page starts.
241
- */
242
- function buildFlowView(network, page) {
243
- let truncated = page.senders.length > 12 || page.receivers.length > 12;
244
- let senders = page.senders.slice(0, 12);
245
- let receivers = page.receivers.slice(0, 12);
246
- for (;;) {
247
- const view = assembleFlowView(network, page, senders, receivers, truncated);
248
- if (fitsFlowBudget(view) || senders.length + receivers.length === 0) return view;
249
- truncated = true;
250
- if (senders.length >= receivers.length) senders = senders.slice(0, -1);
251
- else receivers = receivers.slice(0, -1);
252
- }
253
- }
254
- function formatFlowsUsd(value) {
255
- if (!(value > 0)) return "$0";
256
- if (value < .01) return "under $0.01";
257
- const whole = Math.floor(value);
258
- const cents = Math.round((value - whole) * 100);
259
- if (cents === 100) return formatFlowsUsd(whole + 1);
260
- return `$${whole.toFixed(0).replace(/\B(?=(\d{3})+(?!\d))/g, ",")}.${String(cents).padStart(2, "0")}`;
261
- }
262
- function formatFlowsAge(lastSeenMs, now) {
263
- if (lastSeenMs <= 0) return "at an unknown time";
264
- const date = new Date(lastSeenMs).toISOString().slice(0, 10);
265
- const days = Math.trunc((now.getTime() - lastSeenMs) / 864e5);
266
- if (days < 1) return `${date} (less than a day ago)`;
267
- if (days === 1) return `${date} (1 day ago)`;
268
- return `${date} (${days} days ago)`;
269
- }
270
- /** The role word, with up to three address labels beside it. */
271
- function roleText(node) {
272
- if (!node) return "other";
273
- if (node.labels.length === 0) return node.role;
274
- return `${node.role} (${node.labels.slice(0, 3).join(", ")})`;
275
- }
276
- function sideLines(title, parties) {
277
- if (parties.length === 0) return [`${title}, newest first: none.`];
278
- const lines = [`${title}, newest first (${parties.length}):`];
279
- const perLine = parties.length > 6 ? 2 : 1;
280
- for (let start = 0; start < parties.length; start += perLine) lines.push(`- ${parties.slice(start, start + perLine).join("; ")}`);
281
- return lines;
282
- }
283
- /**
284
- * The text of a node answer: the centre, its role and lifetime totals, then
285
- * every counterparty of the view with its USD, transaction count and last-seen
286
- * date and age. At most FLOWS_SUMMARY_MAX_LINES lines.
287
- */
288
- function flowsSummary(view, now) {
289
- const nodes = new Map(view.nodes.map((node) => [node.address, node]));
290
- const center = nodes.get(view.center);
291
- const party = (address, edge) => `${address} ${roleText(nodes.get(address))}, ${formatFlowsUsd(edge.usd)} in ${edge.tx_count} tx, last seen ${formatFlowsAge(edge.last_seen_ms, now)}`;
292
- const senders = [];
293
- const receivers = [];
294
- for (const edge of view.edges) if (edge.to === view.center) senders.push(party(edge.from, edge));
295
- else receivers.push(party(edge.to, edge));
296
- const body = [
297
- `Money flows of ${view.center} on ${view.network}: ${roleText(center)}; lifetime ${formatFlowsUsd(center?.total_in_usd ?? 0)} in, ${formatFlowsUsd(center?.total_out_usd ?? 0)} out; ${center?.degree_in ?? 0} senders and ${center?.degree_out ?? 0} receivers in the topology graph.`,
298
- ...sideLines("Recent senders", senders),
299
- ...sideLines("Recent receivers", receivers)
300
- ].slice(0, 18);
301
- const footer = pagingLines(view, senders.length, receivers.length, center);
302
- return [...body, ...footer].join("\n");
303
- }
304
- /** Where this page sits, and that the picture loads the rest when an address is clicked. */
305
- function pagingLines(view, shownSenders, shownReceivers, center) {
306
- const totalIn = center?.degree_in ?? 0;
307
- const totalOut = center?.degree_out ?? 0;
308
- const { in_offset: nextIn, out_offset: nextOut } = view.cursor;
309
- const range = (shown, next, total) => shown === 0 ? `none of ${total}` : `${next - shown + 1} to ${next} of ${total}`;
310
- const where = `Showing senders ${range(shownSenders, nextIn, totalIn)} and receivers ${range(shownReceivers, nextOut, totalOut)}, newest first.`;
311
- if (!view.truncated && nextIn >= totalIn && nextOut >= totalOut) return [where];
312
- return [where, "More senders and receivers load when an address in the picture is clicked."];
313
- }
314
- /** A finite number, or a decimal string read as one, or null. */
315
- function flowsNumberOrNull(value) {
316
- if (typeof value === "number") return Number.isFinite(value) ? value : null;
317
- if (typeof value === "string" && value.trim() !== "") {
318
- const parsed = Number(value);
319
- return Number.isFinite(parsed) ? parsed : null;
320
- }
321
- return null;
322
- }
323
- function transferOf(row) {
324
- const amount = typeof row.amount === "number" && Number.isFinite(row.amount) ? row.amount : typeof row.amount === "string" && row.amount.trim() !== "" ? row.amount : null;
325
- return {
326
- tx_id: typeof row.tx_id === "string" ? row.tx_id : "",
327
- block_timestamp: flowsNumberOrNull(row.block_timestamp),
328
- amount,
329
- asset_symbol: typeof row.asset_symbol === "string" && row.asset_symbol !== "" ? row.asset_symbol : null,
330
- amount_usd: flowsNumberOrNull(row.amount_usd)
331
- };
332
- }
333
- /**
334
- * chain-insights.transfers.v1 from the rows of one facts read: newest first,
335
- * at most TRANSFERS_MAX, truncated when more rows than that came back. The
336
- * facts layer takes no ORDER BY, so the order is made here.
337
- */
338
- function buildTransfersView(network, from, to, day, rows) {
339
- const newestFirst = rows.map(transferOf).sort((a, b) => (b.block_timestamp ?? -Infinity) - (a.block_timestamp ?? -Infinity));
340
- return {
341
- schema: TRANSFERS_SCHEMA,
342
- network,
343
- from,
344
- to,
345
- day,
346
- transfers: newestFirst.slice(0, 50),
347
- truncated: newestFirst.length > 50
348
- };
349
- }
350
- function transferLine(transfer) {
351
- return `- ${transfer.block_timestamp === null ? "at an unknown time" : `${new Date(transfer.block_timestamp).toISOString().slice(0, 19).replace("T", " ")} UTC`}, ${transfer.amount === null ? "an unknown amount" : String(transfer.amount)}${transfer.asset_symbol ? ` ${transfer.asset_symbol}` : ""}, ${transfer.amount_usd === null ? "no USD price" : formatFlowsUsd(transfer.amount_usd)}, tx ${transfer.tx_id}`;
352
- }
353
- /** The short text of a link answer: the pair, the day, the count and the newest few transfers. */
354
- function transfersSummary(view) {
355
- const head = `Transfers from ${view.from} to ${view.to} on ${view.day} (UTC) on ${view.network}`;
356
- if (view.transfers.length === 0) return `${head}: none.`;
357
- const lines = [`${head}: ${view.truncated ? `the newest ${view.transfers.length}, and the day holds more` : `${view.transfers.length}`}, newest first.`, ...view.transfers.slice(0, 5).map(transferLine)];
358
- const rest = view.transfers.length - 5;
359
- if (rest > 0) lines.push(`- and ${rest} more in the picture.`);
360
- return lines.join("\n");
361
- }
362
- function errorResult(text) {
363
- return {
364
- content: [{
365
- type: "text",
366
- text
367
- }],
368
- isError: true
369
- };
370
- }
371
- function isRecord$1(value) {
372
- return !!value && typeof value === "object" && !Array.isArray(value);
373
- }
374
- function answerText(answer) {
375
- return (answer.content ?? []).map((block) => block.type === "text" && typeof block.text === "string" ? block.text : "").filter(Boolean).join("\n").trim();
376
- }
377
- /**
378
- * The refusal of a read that did not answer, naming its code first:
379
- * error_detail.code when the graph endpoint sent its typed refusal, the code
380
- * its text starts with otherwise, and graph_query_failed when it names none.
381
- * The view marks the address it was expanding.
382
- */
383
- function refusalText(answer) {
384
- const text = answerText(answer);
385
- const detail = isRecord$1(answer.structuredContent) ? answer.structuredContent.error_detail : void 0;
386
- const detailCode = isRecord$1(detail) && typeof detail.code === "string" ? detail.code : "";
387
- const textCode = CODE_PREFIX.exec(text)?.[1] ?? "";
388
- const code = detailCode || textCode || "graph_query_failed";
389
- const rest = textCode === code ? text.replace(CODE_PREFIX, "") : text;
390
- return rest ? `${code}: ${rest}` : `${code}: the graph endpoint refused the read`;
391
- }
392
- function rowsOf(answer) {
393
- const facts = isRecord$1(answer.structuredContent) ? answer.structuredContent.facts : void 0;
394
- const query = isRecord$1(facts) ? facts.query : void 0;
395
- const results = isRecord$1(query) ? query.results : void 0;
396
- return Array.isArray(results) ? results.filter(isRecord$1) : null;
397
- }
398
- function checkNetwork(args) {
399
- const rawNetwork = typeof args.network === "string" ? args.network.trim().toLowerCase() : "";
400
- if (!rawNetwork) return { error: "invalid_network: network is required; pass robinhood" };
401
- if (rawNetwork !== "robinhood") return { error: `invalid_network: graph_expand reads the robinhood graph only; got "${String(args.network).trim()}"` };
402
- return FLOWS_NETWORK;
403
- }
404
- /** The address of a node or of one end of a link; `name` says which end in a link refusal. */
405
- function checkAddress(raw, name) {
406
- const address = normalizeFlowsAddress(raw);
407
- if (address) return address;
408
- return { error: name ? INVALID_ADDRESS_TEXT.replace("invalid_address:", `invalid_address (${name}):`) : INVALID_ADDRESS_TEXT };
409
- }
410
- function checkDay(raw) {
411
- return normalizeFlowsDay(raw) ?? { error: "invalid_day: day must be a calendar date written YYYY-MM-DD (UTC), for example 2026-07-10" };
412
- }
413
- function checkOffset(value) {
414
- if (value === void 0 || value === null) return 0;
415
- if (typeof value !== "number" || !Number.isInteger(value) || value < 0) return { error: OFFSET_NEGATIVE_TEXT };
416
- if (value > 1e4) return { error: OFFSET_TOO_LARGE_TEXT };
417
- return value;
418
- }
419
- /**
420
- * Read and answer one node page. The reads run one after another: the node
421
- * first, so an address the graph does not hold costs one read, not three; then
422
- * the receivers and the senders. The first read that does not answer ends the
423
- * call.
424
- */
425
- async function runNode(deps, network, address, inOffset, outOffset) {
426
- const unavailable = deps.unavailable?.();
427
- if (unavailable) return errorResult(unavailable);
428
- const rows = {};
429
- for (const read of flowsReadsFor(address, inOffset, outOffset)) {
430
- let answer;
431
- try {
432
- answer = await deps.graphQuery({
433
- network,
434
- query: read.query
435
- });
436
- } catch (err) {
437
- return errorResult(deps.describeFailure(err));
438
- }
439
- if (answer.isError === true) return errorResult(refusalText(answer));
440
- const found = rowsOf(answer);
441
- if (!found) return errorResult("graph_query_failed: the graph endpoint answered without chain-insights.result.v1 rows");
442
- rows[read.id] = found;
443
- if (read.id === "node" && found.length === 0) return errorResult(`${address} is not in the ${network} topology graph`);
444
- }
445
- const view = buildFlowView(network, {
446
- center: rows.node?.[0] ?? {},
447
- senders: rows.in ?? [],
448
- receivers: rows.out ?? [],
449
- inOffset,
450
- outOffset
451
- });
452
- return {
453
- content: [{
454
- type: "text",
455
- text: flowsSummary(view, deps.now ? deps.now() : /* @__PURE__ */ new Date())
456
- }],
457
- structuredContent: view,
458
- isError: false
459
- };
460
- }
461
- /** Read and answer the transfers of one link on one day: a single facts read. */
462
- async function runLink(deps, network, from, to, day) {
463
- const unavailable = deps.unavailable?.();
464
- if (unavailable) return errorResult(unavailable);
465
- let answer;
466
- try {
467
- answer = await deps.graphQuery({
468
- network,
469
- query: transfersReadFor(from, to, day)
470
- });
471
- } catch (err) {
472
- return errorResult(deps.describeFailure(err));
473
- }
474
- if (answer.isError === true) return errorResult(refusalText(answer));
475
- const rows = rowsOf(answer);
476
- if (!rows) return errorResult("graph_query_failed: the graph endpoint answered without chain-insights.result.v1 rows");
477
- const view = buildTransfersView(network, from, to, day, rows);
478
- return {
479
- content: [{
480
- type: "text",
481
- text: transfersSummary(view)
482
- }],
483
- structuredContent: view,
484
- isError: false
485
- };
486
- }
487
- function given(record, keys) {
488
- return keys.some((key) => record[key] !== void 0 && record[key] !== null);
489
- }
490
- /**
491
- * graph_expand, the node form {network, address, in_offset?, out_offset?} or the
492
- * link form {network, from, to, day}. Every argument is checked before the
493
- * first read.
494
- */
495
- async function handleGraphExpand(args, deps) {
496
- const record = isRecord$1(args) ? args : {};
497
- const network = checkNetwork(record);
498
- if (typeof network !== "string") return errorResult(network.error);
499
- const isLink = given(record, [
500
- "from",
501
- "to",
502
- "day"
503
- ]);
504
- if (isLink && given(record, [
505
- "address",
506
- "in_offset",
507
- "out_offset"
508
- ])) return errorResult(BOTH_FORMS_TEXT);
509
- if (isLink) {
510
- const from = checkAddress(record.from, "from");
511
- if (typeof from !== "string") return errorResult(from.error);
512
- const to = checkAddress(record.to, "to");
513
- if (typeof to !== "string") return errorResult(to.error);
514
- const day = checkDay(record.day);
515
- if (typeof day !== "string") return errorResult(day.error);
516
- return runLink(deps, network, from, to, day);
517
- }
518
- const address = checkAddress(record.address);
519
- if (typeof address !== "string") return errorResult(address.error);
520
- const inOffset = checkOffset(record.in_offset);
521
- if (typeof inOffset !== "number") return errorResult(inOffset.error);
522
- const outOffset = checkOffset(record.out_offset);
523
- if (typeof outOffset !== "number") return errorResult(outOffset.error);
524
- return runNode(deps, network, address, inOffset, outOffset);
525
- }
526
- const GRAPH_EXPAND_TITLE = "Expand a node or a link in the picture";
527
- const GRAPH_EXPAND_DESCRIPTION = "Expand an open Chain Insights picture. Called by the view when the investigator clicks, never by the model. A node, {network, address, in_offset?, out_offset?}, loads the newest senders and receivers of one address (12 a side, from the offsets); billed as three graph_query topology reads. A link, {network, from, to, day}, lists the transfers between two addresses on one UTC day (YYYY-MM-DD), newest first, at most 50; billed as one graph_query facts read. Read-only; an argument refused before a read costs nothing.";
528
- //#endregion
529
78
  //#region src/mcp/proxy.ts
530
79
  const LOCAL_TOOL_NAMES = /* @__PURE__ */ new Set([
531
80
  "meta_network_capabilities",
81
+ "meta_schema",
532
82
  "meta_usage_status",
533
83
  "meta_subscription_status",
534
84
  "meta_help",
535
85
  "wallet_balance",
536
86
  "wallet_topup",
537
- GRAPH_EXPAND_TOOL
87
+ require_graph_schema.GRAPH_EXPAND_TOOL
538
88
  ]);
539
- const APP_ONLY_LOCAL_TOOL_NAMES = /* @__PURE__ */ new Set([GRAPH_EXPAND_TOOL]);
89
+ const APP_ONLY_LOCAL_TOOL_NAMES = /* @__PURE__ */ new Set([require_graph_schema.GRAPH_EXPAND_TOOL]);
540
90
  const GRAPH_ARRAY_KEYS = [
541
91
  "nodes",
542
92
  "edges",
@@ -584,6 +134,7 @@ function resolveMcpProxyMode(env = process.env) {
584
134
  const GRAPH_LAYERS_TEXT = "Use USE topology for topology (address/FLOWS_TO/OPERATED_BY/LINKED graph with SWAPPED, ADDED_LIQUIDITY, REMOVED_LIQUIDITY, BRIDGED and the Pool label, unified recent+historical) and USE facts for bounded TRANSFER, SWAP, LIQUIDITY_ADD, LIQUIDITY_REMOVE and BRIDGE_CROSSING rows and enrichment, and USE chain for the chain node's own record of one known transaction, block or the head.";
585
135
  const KNOWN_PUBLIC_TOOL_DESCRIPTIONS = {
586
136
  meta_network_capabilities: "Return the current Chain Insights network and tool support matrix.",
137
+ meta_schema: require_graph_schema.META_SCHEMA_DESCRIPTION,
587
138
  meta_usage_status: "Return the caller's public free graph_query quota for the current UTC day.",
588
139
  meta_subscription_status: "Return the caller's CIA subscription window end, daily allowance, consumption, and tier.",
589
140
  meta_help: "Show a short guide to Chain Insights tools and workflow.",
@@ -636,6 +187,7 @@ const GRAPH_SCHEMA_HINTS = [
636
187
  "- A USE facts SWAP row carries no route: it has no pools and no families column. A read that names one of them, to return it, to filter on it or to order by it, is refused. The route of a swap stays a topology question. For the pools of the swaps of an address, read SWAPPED.pools and SWAPPED.families on USE topology, anchored on the payer or the recipient. SWAPPED has one link per payer, recipient, sold asset and bought asset, so its pools cover every route on the link, not one route.",
637
188
  "- 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. is_exchange is absent unless true, so a labelled node with no is_exchange is walked through, and is_scam, is_victim and is_sanctioned do not end a walk. At a Pool, follow the pool trace rule above.",
638
189
  "- Pool guard: a trace walks FLOWS_TO and SWAPPED, so it crosses a swap from payer to recipient without passing through the pool. A walk may end at a Pool, but never starts at one or passes through one: its start and every address in its middle stay off a Pool. A fixed-hop walk adds WHERE NOT src:Pool AND NOT mid:Pool, each its own AND term, never inside an OR. A quantified or shortest-path walk puts the guards inside the path pattern, on the start and on up to 4 guarded hops before one last hop: MATCH p = SHORTEST 1 (a:Address {address: $from} WHERE NOT a:Pool) (()-[:FLOWS_TO|SWAPPED]-(via:Address) WHERE NOT via:Pool){0,4} ()-[:FLOWS_TO|SWAPPED]-(b:Address {address: $to}) RETURN [n IN nodes(p) | n.address] AS route LIMIT 5. ANY SHORTEST takes the same pattern. A route search asks for one path. An open target from one address: MATCH SHORTEST 1 (a:Address {address: $addr} WHERE NOT a:Pool) (()-[:FLOWS_TO|SWAPPED]-(via:Address) WHERE NOT via:Pool){0,4} ()-[:FLOWS_TO|SWAPPED]-(b:Address) RETURN b.address LIMIT 50. Use these shapes as written, changing only the addresses and the RETURN. A WHERE placed after a SHORTEST pattern runs after the shortest route is chosen, so it drops a route that crosses a pool instead of finding the route that avoids it.",
190
+ "- Call meta_schema {network} first when you need field names; it is cached for 24 hours. The two discovery reads below are the fallback.",
639
191
  "- Start schema discovery with endpoint-safe property reads: MATCH (n:Address) RETURN n.address AS address, n.network AS network, n.labels AS labels, n.last_activity_timestamp AS last_activity_timestamp LIMIT 20",
640
192
  "- 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",
641
193
  "- Anchor every topology read that filters on a link property: put an address in its pattern. Without one, a read starts from every link of the type it names, and you should not count on the filter to narrow that: WHERE x.strength = 'swap' on SWAPPED checks every SWAPPED link, LIMIT stops the read only after enough rows match, and a filter that matches few or none can run to the 60 s topology limit and fail with query_timeout. Example: MATCH (a:Address {address: $addr})-[x:SWAPPED]->(b:Address) WHERE x.swap_count >= 2 RETURN b.address, x.swap_count LIMIT 25. Pick an address with few links: degree_out and degree_in are a rough guide, because they count neighbours, not links, and an address with hundreds of thousands of neighbours can fail the same way. Discovery probes with LIMIT and no filter stay valid. The queries of one batch share a 100 s budget; USE facts queries stop at 30 s.",
@@ -930,6 +482,11 @@ function registerLocalPrompts(server) {
930
482
  description: "Inspect supported networks and available tools before selecting a network.",
931
483
  argsSchema: {}
932
484
  }, async () => promptResult("Use Chain Insights meta_network_capabilities. Report only the supported networks and available tools exactly as returned; do not infer unsupported networks.", "Network capabilities"));
485
+ server.registerPrompt("meta-schema", {
486
+ title: "Graph Schema",
487
+ description: "Read the live graph schema of one network before writing a query.",
488
+ argsSchema: { network: NETWORK_SCHEMA }
489
+ }, async ({ network }) => promptResult(`Use Chain Insights meta_schema with network ${network}. Report the labels, link types and fields exactly as returned; do not invent fields.`, "Graph schema"));
933
490
  server.registerPrompt("meta-usage-status", {
934
491
  title: "Usage Status",
935
492
  description: "Check the caller's public free graph_query quota.",
@@ -1054,7 +611,7 @@ async function createProxy() {
1054
611
  const { loadConfig } = await Promise.resolve().then(() => require("./config-BxtMoo9c.cjs")).then((n) => n.config_exports);
1055
612
  const { activeDataDir, findActiveWorkspace } = await Promise.resolve().then(() => require("./active-Bc13hJIm.cjs")).then((n) => n.active_exports);
1056
613
  const { createConfiguredGraphMcpFetch, resolveGraphMcpEndpoint } = await Promise.resolve().then(() => require("./client-Ypw9BNbn.cjs")).then((n) => n.client_exports);
1057
- const { loadSchema, saveSchema } = await Promise.resolve().then(() => require("./schema-cache-n7Gbhvsj.cjs"));
614
+ const { loadSchema, saveSchema } = await Promise.resolve().then(() => require("./schema-cache-DwddPLcY.cjs"));
1058
615
  const proxyMode = resolveMcpProxyMode();
1059
616
  const workspaceArtifactsEnabled = proxyMode === "workspace";
1060
617
  const loadedConfig = await loadConfig();
@@ -1183,6 +740,28 @@ async function createProxy() {
1183
740
  }
1184
741
  return jsonTextResult(cleanNetworkCapabilities(void 0));
1185
742
  });
743
+ const schemaDependencies = {
744
+ endpoint: graphMcpEndpoint,
745
+ withClient: async (fn) => {
746
+ if (!remoteConnected) throw new require_graph_schema.GraphSchemaError(`${remoteUnavailableMessage ?? `Chain Insights Graph is not connected at ${graphMcpEndpoint}`}. Restart the Chain Insights MCP proxy after the endpoint is reachable.`);
747
+ return fn(remoteClient);
748
+ },
749
+ describeFailure: (err) => remoteCallFailureText("meta_schema", err)
750
+ };
751
+ server.registerTool("meta_schema", {
752
+ title: require_graph_schema.META_SCHEMA_TITLE,
753
+ description: KNOWN_PUBLIC_TOOL_DESCRIPTIONS.meta_schema,
754
+ inputSchema: {
755
+ network: NETWORK_SCHEMA,
756
+ refresh: zod.boolean().optional().describe("Rebuild the schema now instead of reading the 24 hour cache.")
757
+ },
758
+ annotations: {
759
+ readOnlyHint: true,
760
+ destructiveHint: false,
761
+ idempotentHint: true,
762
+ openWorldHint: true
763
+ }
764
+ }, async (args) => require_graph_schema.handleMetaSchema(args, schemaDependencies));
1186
765
  server.registerTool("meta_usage_status", {
1187
766
  title: "Usage Status",
1188
767
  description: KNOWN_PUBLIC_TOOL_DESCRIPTIONS.meta_usage_status,
@@ -1317,21 +896,21 @@ async function createProxy() {
1317
896
  describeFailure: (err) => remoteCallFailureText("graph_query", err),
1318
897
  unavailable: () => remoteConnected ? void 0 : `${remoteUnavailableMessage ?? `Chain Insights Graph is not connected at ${graphMcpEndpoint}`}. Restart the Chain Insights MCP proxy after the endpoint is reachable.`
1319
898
  };
1320
- server.registerTool(GRAPH_EXPAND_TOOL, {
1321
- title: GRAPH_EXPAND_TITLE,
1322
- description: GRAPH_EXPAND_DESCRIPTION,
899
+ server.registerTool(require_graph_schema.GRAPH_EXPAND_TOOL, {
900
+ title: require_graph_schema.GRAPH_EXPAND_TITLE,
901
+ description: require_graph_schema.GRAPH_EXPAND_DESCRIPTION,
1323
902
  inputSchema: {
1324
903
  network: zod.string(),
1325
904
  address: zod.string().optional(),
1326
- in_offset: zod.number().int().min(0).max(FLOWS_MAX_OFFSET).optional(),
1327
- out_offset: zod.number().int().min(0).max(FLOWS_MAX_OFFSET).optional(),
905
+ in_offset: zod.number().int().min(0).max(require_graph_schema.FLOWS_MAX_OFFSET).optional(),
906
+ out_offset: zod.number().int().min(0).max(require_graph_schema.FLOWS_MAX_OFFSET).optional(),
1328
907
  from: zod.string().optional(),
1329
908
  to: zod.string().optional(),
1330
909
  day: zod.string().optional()
1331
910
  },
1332
911
  annotations: VIEW_TOOL_ANNOTATIONS,
1333
912
  _meta: APP_ONLY_TOOL_META
1334
- }, async (args) => handleGraphExpand(args, flowsDependencies));
913
+ }, async (args) => require_graph_schema.handleGraphExpand(args, flowsDependencies));
1335
914
  server.registerTool("meta_help", {
1336
915
  title: "Chain Insights Help",
1337
916
  description: KNOWN_PUBLIC_TOOL_DESCRIPTIONS.meta_help,
@@ -1352,6 +931,7 @@ async function createProxy() {
1352
931
  "",
1353
932
  "Investigation tools:",
1354
933
  "- meta_network_capabilities: inspect supported networks and available tools.",
934
+ "- meta_schema: read the live graph schema of one network: labels, link types and field names. Cached for 24 hours.",
1355
935
  "- meta_usage_status: check the caller public free graph_query quota.",
1356
936
  "- meta_subscription_status: check the caller CIA subscription window end, daily allowance, consumption, and tier.",
1357
937
  "- graph_query: run read-only GQL/Cypher through the universal graph endpoint. Use USE topology or USE facts.",
@@ -1367,6 +947,7 @@ async function createProxy() {
1367
947
  "",
1368
948
  "Available graph-backed tools:",
1369
949
  "- meta_network_capabilities: inspect supported networks and available tools.",
950
+ "- meta_schema: read the live graph schema of one network: labels, link types and field names. Cached for 24 hours.",
1370
951
  "- meta_usage_status: check the caller public free graph_query quota.",
1371
952
  "- meta_subscription_status: check the caller CIA subscription window end, daily allowance, consumption, and tier.",
1372
953
  "- graph_query: run read-only GQL/Cypher through the universal graph endpoint. Use USE topology or USE facts.",
@@ -1 +1 @@
1
- {"version":3,"file":"mcp-proxy.d.cts","names":[],"sources":["../src/mcp/proxy.ts"],"mappings":";;qBAuDa;qBACA;;;;;wBAqBG;YAkBJ;wBAEI,oBAAoB,MAAK,OAAO,aAA2B;KA8BtE,iBAAiB,eAAe,EAAE;wBAwFvB,2BAA2B,mBAAmB;;;;;;;;wBAilBxC,eAAe"}
1
+ {"version":3,"file":"mcp-proxy.d.cts","names":[],"sources":["../src/mcp/proxy.ts"],"mappings":";;qBA+Da;qBACA;;;;;wBAqBG;YAkBJ;wBAEI,oBAAoB,MAAK,OAAO,aAA2B;KA+BtE,iBAAiB,eAAe,EAAE;wBAyFvB,2BAA2B,mBAAmB;;;;;;;;wBA+lBxC,eAAe"}
@@ -1 +1 @@
1
- {"version":3,"file":"mcp-proxy.d.mts","names":[],"sources":["../src/mcp/proxy.ts"],"mappings":";;qBAuDa;qBACA;;;;;wBAqBG;YAkBJ;wBAEI,oBAAoB,MAAK,OAAO,aAA2B;KA8BtE,iBAAiB,eAAe,EAAE;wBAwFvB,2BAA2B,mBAAmB;;;;;;;;wBAilBxC,eAAe"}
1
+ {"version":3,"file":"mcp-proxy.d.mts","names":[],"sources":["../src/mcp/proxy.ts"],"mappings":";;qBA+Da;qBACA;;;;;wBAqBG;YAkBJ;wBAEI,oBAAoB,MAAK,OAAO,aAA2B;KA+BtE,iBAAiB,eAAe,EAAE;wBAyFvB,2BAA2B,mBAAmB;;;;;;;;wBA+lBxC,eAAe"}