@secondlayer/mcp 7.2.1 → 7.4.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.
package/dist/bin.js CHANGED
@@ -21,13 +21,20 @@ function isHostedArchiveUrl(url) {
21
21
 
22
22
  // src/resources.ts
23
23
  import { CHAIN_TRIGGER_FIELDS } from "@secondlayer/shared";
24
+ import { BOOTSTRAP_STEP } from "@secondlayer/shared/archive/instance-diagnosis";
24
25
  import { TRAIT_STANDARDS } from "@secondlayer/stacks/clarity";
25
26
  import { filterFieldsByType } from "@secondlayer/subgraphs";
26
27
  import { TYPE_MAP } from "@secondlayer/subgraphs/schema";
27
28
 
28
29
  // src/lib/client.ts
29
- import { SecondLayer, resolveApiKey } from "@secondlayer/sdk";
30
+ import {
31
+ SecondLayer,
32
+ resolveAccountKey,
33
+ resolveApiKey
34
+ } from "@secondlayer/sdk";
30
35
  var instance = null;
36
+ var HOSTED_KEY_HINT = "set SECONDLAYER_API_KEY (sk-sl_*) for credits; INSTANCE_TOKEN is the instance";
37
+ var DEFAULT_ARCHIVE_OPS_URL = "https://api.secondlayer.tools";
31
38
  function readApiKey() {
32
39
  return resolveApiKey();
33
40
  }
@@ -45,10 +52,31 @@ function getClient() {
45
52
  }
46
53
  return instance;
47
54
  }
48
- var keyHint = " — set INSTANCE_TOKEN from `sl init` for writes (SL_API_KEY is a legacy alias)";
55
+ function readArchiveApiKey() {
56
+ return resolveAccountKey();
57
+ }
58
+ function getArchiveOpsClient() {
59
+ const accountKey = readArchiveApiKey();
60
+ if (!accountKey) {
61
+ throw new Error(HOSTED_KEY_HINT);
62
+ }
63
+ const archiveOpsUrl = process.env.SL_CREDITS_API_URL || process.env.ARCHIVE_OPS_API_URL || DEFAULT_ARCHIVE_OPS_URL;
64
+ return new SecondLayer({
65
+ accountKey,
66
+ origin: "mcp",
67
+ archiveOpsUrl
68
+ });
69
+ }
70
+ var keyHint = " — set INSTANCE_TOKEN from `sl init` for writes";
49
71
  async function apiRequest(method, path, body) {
50
- const apiKey = readApiKey();
51
72
  const baseUrl = process.env.SECONDLAYER_API_URL || process.env.SL_API_URL || "http://127.0.0.1:3800";
73
+ let host = "";
74
+ try {
75
+ host = new URL(baseUrl).hostname;
76
+ } catch {
77
+ host = "";
78
+ }
79
+ const apiKey = host === "api.secondlayer.tools" ? resolveAccountKey() : readApiKey();
52
80
  const res = await fetch(`${baseUrl}${path}`, {
53
81
  method,
54
82
  headers: {
@@ -158,7 +186,11 @@ var PRODUCT_BLURBS = {
158
186
  subgraphs: "author/scaffold/deploy/query custom indexes",
159
187
  subscriptions: "webhook delivery on subgraph rows or raw chain events",
160
188
  account: "identity and self-provisioned API keys",
161
- codegen: "ORM schemas for the tables you read"
189
+ codegen: "ORM schemas for the tables you read",
190
+ instance: "decoder health and empty-index diagnosis",
191
+ archive: "signed archive verify, bootstrap/repair, quote, latest pointer",
192
+ setup: "one-command self-host onboarding",
193
+ credits: "archive credits balance at api.secondlayer.tools"
162
194
  };
163
195
  var PRODUCT_ORDER = [
164
196
  "index",
@@ -167,12 +199,17 @@ var PRODUCT_ORDER = [
167
199
  "subgraphs",
168
200
  "subscriptions",
169
201
  "account",
170
- "codegen"
202
+ "codegen",
203
+ "instance",
204
+ "archive",
205
+ "setup",
206
+ "credits"
171
207
  ];
172
208
  function buildCapabilities() {
173
209
  const byPrefix = new Map;
174
210
  for (const name of getRegisteredToolNames()) {
175
- const prefix = name.slice(0, name.indexOf("_"));
211
+ const sep = name.indexOf("_");
212
+ const prefix = sep === -1 ? name : name.slice(0, sep);
176
213
  const tools = byPrefix.get(prefix) ?? [];
177
214
  tools.push(name);
178
215
  byPrefix.set(prefix, tools);
@@ -206,6 +243,7 @@ async function buildContext(deps = { clientProvider: getClient }) {
206
243
  return field.error ? `unavailable: ${field.error.message}` : unavailable;
207
244
  };
208
245
  const snap = await deps.clientProvider().context().catch(() => null);
246
+ const instance2 = snap?.instance?.value ? snap.instance.value : orNull(snap?.instance);
209
247
  return {
210
248
  authState: {
211
249
  apiKeySet: Boolean(readApiKey())
@@ -216,10 +254,12 @@ async function buildContext(deps = { clientProvider: getClient }) {
216
254
  indexTip: orNull(snap?.indexTip),
217
255
  subgraphs: snap?.subgraphs.value ? snap.subgraphs.value.map(formatSubgraphSummary) : orNull(snap?.subgraphs),
218
256
  subscriptions: orNull(snap?.subscriptions),
219
- activeOperations: orNull(snap?.activeOperations)
257
+ activeOperations: orNull(snap?.activeOperations),
258
+ instance: instance2
220
259
  },
221
260
  whatYouCanDo: buildCapabilities(),
222
- readAuthTiers: READ_AUTH_TIERS
261
+ readAuthTiers: READ_AUTH_TIERS,
262
+ ...snap?.instance?.value?.state === "empty-index" ? { nextStep: BOOTSTRAP_STEP } : {}
223
263
  };
224
264
  }
225
265
  function registerResources(server) {
@@ -293,18 +333,43 @@ function registerAccountTools(server) {
293
333
  }, async ({ name }) => jsonResponse(await apiRequest("POST", "/api/keys", { name })));
294
334
  }
295
335
 
336
+ // src/tools/archive.ts
337
+ import { z as z2 } from "zod";
338
+ var FLOW = ["bootstrap", "repair"];
339
+ function registerArchiveTools(server, clientProvider = getClient, archiveOpsClientProvider = getArchiveOpsClient) {
340
+ defineTool(server, "archive_verify", "Read-only, free compare of this instance against a signed archive (POST /v1/archive/verify). unanchored means pin a key or check the URL — not that the instance is fine. After bootstrap, poll instance_status until decoders ok, then this, then codegen_index_schema. Do not download parquet.", {
341
+ against: z2.string().describe("Archive manifest URL"),
342
+ fromBlock: z2.number().int().nonnegative().optional().describe("First height (inclusive)"),
343
+ toBlock: z2.number().int().nonnegative().optional().describe("Last height (inclusive)"),
344
+ target: z2.string().optional().describe("Verify target (default raw)")
345
+ }, async ({ against, fromBlock, toBlock, target }) => jsonResponse(await clientProvider().archive.verify({
346
+ against,
347
+ fromBlock,
348
+ toBlock,
349
+ target
350
+ })));
351
+ defineTool(server, "archive_latest", "Signed pointer to the official archive tree (hosted). Needs SECONDLAYER_API_KEY (sk-sl_*), not INSTANCE_TOKEN. Use the returned origin as --against for archive_bootstrap. Do not download parquet.", {
352
+ against: z2.string().optional().describe("Override latest.json URL (default official tree)")
353
+ }, async ({ against }) => jsonResponse(await archiveOpsClientProvider().archive.latest(against)));
354
+ defineTool(server, "archive_quote", "Price a hosted archive fetch (metered). Needs SECONDLAYER_API_KEY (sk-sl_*), not INSTANCE_TOKEN. Quote happens here; bootstrap/repair also quote inside the CLI. Do not download parquet.", {
355
+ paths: z2.array(z2.string()).describe("Partition paths to price"),
356
+ flow: z2.enum(FLOW).describe("bootstrap or repair")
357
+ }, async ({ paths, flow }) => jsonResponse(await archiveOpsClientProvider().archive.quote({ paths, flow })));
358
+ defineTool(server, "credits_balance", "Archive credits balance at api.secondlayer.tools. Needs SECONDLAYER_API_KEY (sk-sl_*); INSTANCE_TOKEN is the instance.", {}, async () => jsonResponse(await archiveOpsClientProvider().archive.credits.balance()));
359
+ }
360
+
296
361
  // src/tools/codegen.ts
297
362
  import {
298
363
  generateIndexSchema
299
364
  } from "@secondlayer/subgraphs";
300
- import { z as z2 } from "zod";
365
+ import { z as z3 } from "zod";
301
366
  var TARGETS = ["prisma", "kysely", "drizzle", "json-schema"];
302
367
  function registerCodegenTools(server) {
303
368
  defineTool(server, "codegen_index_schema", "Generate an ORM schema for the Index tables (blocks, transactions, decoded_events, …) — the same output as `sl codegen index`. Returns the file contents as text; write it wherever your project keeps its schema. Use `tables` to emit only what you read.", {
304
- target: z2.enum(TARGETS).optional().describe("Output flavor (default kysely)"),
305
- tables: z2.array(z2.string()).optional().describe("Restrict to these Index tables (default: all)"),
306
- schemaName: z2.string().optional().describe("Postgres schema to qualify table names with"),
307
- datasourceEnv: z2.string().optional().describe("Prisma only: datasource url env var (default DATABASE_URL)")
369
+ target: z3.enum(TARGETS).optional().describe("Output flavor (default kysely)"),
370
+ tables: z3.array(z3.string()).optional().describe("Restrict to these Index tables (default: all)"),
371
+ schemaName: z3.string().optional().describe("Postgres schema to qualify table names with"),
372
+ datasourceEnv: z3.string().optional().describe("Prisma only: datasource url env var (default DATABASE_URL)")
308
373
  }, ({ target, tables, schemaName, datasourceEnv }) => textResponse(generateIndexSchema(target ?? "kysely", {
309
374
  tables,
310
375
  schemaName,
@@ -313,17 +378,17 @@ function registerCodegenTools(server) {
313
378
  }
314
379
 
315
380
  // src/tools/contracts.ts
316
- import { z as z3 } from "zod";
381
+ import { z as z4 } from "zod";
317
382
  function registerContractTools(server, clientProvider = getClient) {
318
383
  defineTool(server, "contracts_find", 'Discover deployed Stacks contracts conforming to a trait (e.g. "sip-010", "sip-009", "sip-013"). The discovery endpoint for "which contracts implement X". Reads are public.', {
319
- trait: z3.string().describe('Required. Trait to match (e.g. "sip-010").'),
320
- conformance: z3.enum(["declared", "inferred", "any"]).optional().describe("declared = parsed from source, inferred = ABI shape-match, any = either (default)"),
321
- include: z3.literal("abi").optional().describe(`Set to "abi" to include each contract's full ABI`),
322
- limit: z3.number().optional().describe("Page size, 1–500 (default 100)"),
323
- cursor: z3.string().optional().describe("Opaque cursor from a prior response's next_cursor")
384
+ trait: z4.string().describe('Required. Trait to match (e.g. "sip-010").'),
385
+ conformance: z4.enum(["declared", "inferred", "any"]).optional().describe("declared = parsed from source, inferred = ABI shape-match, any = either (default)"),
386
+ include: z4.literal("abi").optional().describe(`Set to "abi" to include each contract's full ABI`),
387
+ limit: z4.number().optional().describe("Page size, 1–500 (default 100)"),
388
+ cursor: z4.string().optional().describe("Opaque cursor from a prior response's next_cursor")
324
389
  }, async (params) => jsonResponse(await clientProvider().contracts.list(params)));
325
390
  defineTool(server, "contracts_get_abi", "Fetch a single deployed contract's ABI from the registry (prod-safe). Returns the contract's metadata + full ABI (functions, maps, variables, fungible/non-fungible tokens). Returns not_found if the contract isn't in the registry. Use it to inspect a contract before subgraphs_scaffold.", {
326
- contractId: z3.string().describe("Fully qualified contract id (e.g. SP….amm-pool-v2-01)")
391
+ contractId: z4.string().describe("Fully qualified contract id (e.g. SP….amm-pool-v2-01)")
327
392
  }, async ({ contractId }) => {
328
393
  const contract = await clientProvider().contracts.get(contractId, {
329
394
  includeAbi: true
@@ -340,14 +405,14 @@ function registerContractTools(server, clientProvider = getClient) {
340
405
 
341
406
  // src/tools/index.ts
342
407
  import { DECODED_EVENT_TYPES } from "@secondlayer/shared";
343
- import { z as z4 } from "zod";
408
+ import { z as z5 } from "zod";
344
409
  var INDEX_EVENT_TYPES = DECODED_EVENT_TYPES;
345
410
  var rangeFilters = {
346
- contractId: z4.string().optional().describe("Filter by contract id"),
347
- fromHeight: z4.number().optional().describe("Start block height (inclusive)"),
348
- toHeight: z4.number().optional().describe("End block height (inclusive)"),
349
- cursor: z4.string().optional().describe("Opaque cursor from a prior response's next_cursor"),
350
- limit: z4.number().optional().describe("Max rows for this page")
411
+ contractId: z5.string().optional().describe("Filter by contract id"),
412
+ fromHeight: z5.number().optional().describe("Start block height (inclusive)"),
413
+ toHeight: z5.number().optional().describe("End block height (inclusive)"),
414
+ cursor: z5.string().optional().describe("Opaque cursor from a prior response's next_cursor"),
415
+ limit: z5.number().optional().describe("Max rows for this page")
351
416
  };
352
417
  var heightFilters = {
353
418
  fromHeight: rangeFilters.fromHeight,
@@ -358,52 +423,62 @@ var heightFilters = {
358
423
  function registerIndexTools(server, clientProvider = getClient) {
359
424
  defineTool(server, "index_ft_transfers", "List decoded SIP-010 fungible-token transfers from Index. Reads are keyless.", {
360
425
  ...rangeFilters,
361
- sender: z4.string().optional().describe("Filter by sender principal"),
362
- recipient: z4.string().optional().describe("Filter by recipient principal"),
363
- assetIdentifier: z4.string().optional().describe("Filter by asset identifier (contract::asset), e.g. SP…sbtc-token::sbtc-token")
426
+ sender: z5.string().optional().describe("Filter by sender principal"),
427
+ recipient: z5.string().optional().describe("Filter by recipient principal"),
428
+ assetIdentifier: z5.string().optional().describe("Filter by asset identifier (contract::asset), e.g. SP…sbtc-token::sbtc-token")
364
429
  }, async (params) => jsonResponse(await clientProvider().index.ftTransfers.list(params)));
365
430
  defineTool(server, "index_nft_transfers", "List decoded SIP-009 non-fungible-token transfers from Index. Reads are keyless.", {
366
431
  ...rangeFilters,
367
- sender: z4.string().optional().describe("Filter by sender principal"),
368
- recipient: z4.string().optional().describe("Filter by recipient principal"),
369
- assetIdentifier: z4.string().optional().describe("Filter by asset identifier (contract::asset)")
432
+ sender: z5.string().optional().describe("Filter by sender principal"),
433
+ recipient: z5.string().optional().describe("Filter by recipient principal"),
434
+ assetIdentifier: z5.string().optional().describe("Filter by asset identifier (contract::asset)")
370
435
  }, async (params) => jsonResponse(await clientProvider().index.nftTransfers.list(params)));
371
436
  defineTool(server, "index_events", "List decoded chain events from the Index by event type. Use this for event types without a dedicated tool (stx_*, ft_mint/burn, nft_mint/burn, print), and for trait-scoped queries: set `trait` (e.g. sip-010) to match all contracts conforming to a standard — pair with contracts_find to discover traits. For ft/nft transfers without a trait prefer index_ft_transfers / index_nft_transfers.", {
372
- eventType: z4.enum(INDEX_EVENT_TYPES).describe("Required. Decoded event type to list."),
437
+ eventType: z5.enum(INDEX_EVENT_TYPES).describe("Required. Decoded event type to list."),
373
438
  ...rangeFilters,
374
- sender: z4.string().optional().describe("Filter by sender principal"),
375
- recipient: z4.string().optional().describe("Filter by recipient principal"),
376
- assetIdentifier: z4.string().optional().describe("Filter by asset identifier where applicable"),
377
- trait: z4.string().optional().describe("Match contracts conforming to a trait/standard (e.g. sip-010). Mutually exclusive with contractId; contract-keyed event types only."),
378
- txContext: z4.boolean().optional().describe("Join the submitting transaction into each event (tx_sender, tx_type, tx_status, tx_contract_id, tx_function_name). For print events it's the only source of the submitting sender.")
439
+ sender: z5.string().optional().describe("Filter by sender principal"),
440
+ recipient: z5.string().optional().describe("Filter by recipient principal"),
441
+ assetIdentifier: z5.string().optional().describe("Filter by asset identifier where applicable"),
442
+ trait: z5.string().optional().describe("Match contracts conforming to a trait/standard (e.g. sip-010). Mutually exclusive with contractId; contract-keyed event types only."),
443
+ txContext: z5.boolean().optional().describe("Join the submitting transaction into each event (tx_sender, tx_type, tx_status, tx_contract_id, tx_function_name). For print events it's the only source of the submitting sender.")
379
444
  }, async (params) => jsonResponse(await clientProvider().index.events.list(params)));
380
445
  defineTool(server, "index_contract_calls", "List decoded contract calls from the Index (function name, args, result). Set `trait` (e.g. sip-010) to match calls to all contracts conforming to a standard. Note: contract-call cursors are a SEPARATE keyspace from event cursors — they are not interchangeable.", {
381
446
  ...rangeFilters,
382
- functionName: z4.string().optional().describe("Filter by called function name"),
383
- sender: z4.string().optional().describe("Filter by caller principal"),
384
- trait: z4.string().optional().describe("Match contracts conforming to a trait/standard (e.g. sip-010). Mutually exclusive with contractId.")
447
+ functionName: z5.string().optional().describe("Filter by called function name"),
448
+ sender: z5.string().optional().describe("Filter by caller principal"),
449
+ trait: z5.string().optional().describe("Match contracts conforming to a trait/standard (e.g. sip-010). Mutually exclusive with contractId.")
385
450
  }, async (params) => jsonResponse(await clientProvider().index.contractCalls.list(params)));
386
451
  defineTool(server, "index_blocks", "List decoded blocks from Index. Reads are keyless.", { ...heightFilters }, async (params) => jsonResponse(await clientProvider().index.blocks.list(params)));
387
452
  defineTool(server, "index_transactions", "List decoded transactions from Index. Filter by type, sender, or contract. Reads are keyless.", {
388
453
  ...rangeFilters,
389
- type: z4.string().optional().describe("Filter by transaction type"),
390
- sender: z4.string().optional().describe("Filter by sender principal")
454
+ type: z5.string().optional().describe("Filter by transaction type"),
455
+ sender: z5.string().optional().describe("Filter by sender principal")
391
456
  }, async (params) => jsonResponse(await clientProvider().index.transactions.list(params)));
392
457
  defineTool(server, "index_print_schema", "Empirical per-topic print payload schemas for a contract, inferred from sampled on-chain events: each topic's fields with observed Clarity types, decoded TS types, subgraph column types, and presence rates. Use before writing print_event subgraph handlers to learn what's on e.data. Anonymous read.", {
393
- contractId: z4.string().describe("Contract id (SP….name) whose print events to profile")
458
+ contractId: z5.string().describe("Contract id (SP….name) whose print events to profile")
394
459
  }, async (params) => jsonResponse(await clientProvider().index.printSchema(params.contractId)));
395
460
  defineTool(server, "index_discover", "Discover the Index vocabulary: every event type and its columns, allowed/equality filters, and required-non-null fields (and which types accept `trait`). Read this before building Index queries instead of guessing filters. Anonymous read.", {}, async () => jsonResponse(await clientProvider().index.discover()));
396
461
  defineTool(server, "batch_query", "Run up to 10 public /v1 reads in one round trip (POST /v1/batch). Each item keeps its own auth/quota/pay-per-call semantics; results return in order with per-item status. Paths must start with /v1/index, /v1/subgraphs, /v1/streams, or /v1/contracts.", {
397
- requests: z4.array(z4.object({
398
- path: z4.string().describe("Public /v1 read path"),
399
- params: z4.record(z4.string(), z4.string()).optional()
462
+ requests: z5.array(z5.object({
463
+ path: z5.string().describe("Public /v1 read path"),
464
+ params: z5.record(z5.string(), z5.string()).optional()
400
465
  })).min(1).max(10).describe("Read descriptors, executed concurrently")
401
466
  }, async (params) => jsonResponse(await clientProvider().batch(params.requests)));
402
467
  }
403
468
 
469
+ // src/tools/instance.ts
470
+ function registerInstanceTools(server, clientProvider = getClient) {
471
+ defineTool(server, "instance_status", "Decoder health and empty-index diagnosis from GET /public/status. If state is empty-index, next tool is archive_bootstrap or setup. Poll until index.decoders are ok before treating Index as ready — do not start decoders. Then archive_verify, then codegen_index_schema. Do not download parquet.", {}, async () => {
472
+ const client = clientProvider();
473
+ const status = await client.instance.status();
474
+ const diagnosis = await client.instance.diagnose();
475
+ return jsonResponse({ status, diagnosis });
476
+ });
477
+ }
478
+
404
479
  // src/tools/scaffold.ts
405
480
  import { generateSubgraphCode } from "@secondlayer/scaffold";
406
- import { z as z5 } from "zod";
481
+ import { z as z6 } from "zod";
407
482
  async function fetchAbi(clientProvider, contractId) {
408
483
  const contract = await clientProvider().contracts.get(contractId, {
409
484
  includeAbi: true
@@ -418,8 +493,8 @@ async function fetchAbi(clientProvider, contractId) {
418
493
  }
419
494
  function registerScaffoldTools(server, clientProvider = getClient) {
420
495
  defineTool(server, "subgraphs_scaffold", "Generate a subgraph scaffold from a deployed Stacks contract. Fetches the ABI automatically. Returns TypeScript source — review it, then pass it to subgraphs_deploy.", {
421
- contractId: z5.string().describe("Fully qualified contract ID (e.g. SP102V8P0F7JX67ARQ77WEA3D3CFB5XW39REDT0AM.amm-pool-v2-01)"),
422
- subgraphName: z5.string().optional().describe("Override the subgraph name (defaults to contract name)")
496
+ contractId: z6.string().describe("Fully qualified contract ID (e.g. SP102V8P0F7JX67ARQ77WEA3D3CFB5XW39REDT0AM.amm-pool-v2-01)"),
497
+ subgraphName: z6.string().optional().describe("Override the subgraph name (defaults to contract name)")
423
498
  }, async ({ contractId, subgraphName }) => {
424
499
  const { functions } = await fetchAbi(clientProvider, contractId);
425
500
  const code = generateSubgraphCode(contractId, functions, subgraphName);
@@ -427,36 +502,245 @@ function registerScaffoldTools(server, clientProvider = getClient) {
427
502
  });
428
503
  }
429
504
 
505
+ // src/tools/setup.ts
506
+ import { z as z7 } from "zod";
507
+
508
+ // src/lib/exec-cli.ts
509
+ import {
510
+ spawn
511
+ } from "node:child_process";
512
+ var ALLOWED = ["setup", "bootstrap", "repair", "verify"];
513
+ var TIMEOUT_MS = {
514
+ setup: 15 * 60 * 1000,
515
+ bootstrap: 10 * 60 * 1000,
516
+ repair: 10 * 60 * 1000,
517
+ verify: 2 * 60 * 1000
518
+ };
519
+ var VALUE_FLAGS = new Set([
520
+ "--against",
521
+ "--from-block",
522
+ "--to-block",
523
+ "--network",
524
+ "--node-mode",
525
+ "--dir"
526
+ ]);
527
+ var BOOL_FLAGS = new Set(["--yes", "--json", "--apply", "--skip-bootstrap"]);
528
+ var FLAGS_BY_CMD = {
529
+ setup: new Set([
530
+ "--yes",
531
+ "--network",
532
+ "--node-mode",
533
+ "--against",
534
+ "--dir",
535
+ "--skip-bootstrap"
536
+ ]),
537
+ bootstrap: new Set([
538
+ "--against",
539
+ "--yes",
540
+ "--json",
541
+ "--from-block",
542
+ "--to-block"
543
+ ]),
544
+ repair: new Set([
545
+ "--against",
546
+ "--json",
547
+ "--apply",
548
+ "--from-block",
549
+ "--to-block",
550
+ "--yes"
551
+ ]),
552
+ verify: new Set(["--against", "--json", "--from-block", "--to-block"])
553
+ };
554
+
555
+ class ExecCliError extends Error {
556
+ constructor(message) {
557
+ super(message);
558
+ this.name = "ExecCliError";
559
+ }
560
+ }
561
+ function isUnsafeArg(arg) {
562
+ if (arg.includes("\x00"))
563
+ return true;
564
+ if (/[\n\r]/.test(arg))
565
+ return true;
566
+ return /^[;|&]/.test(arg.trim());
567
+ }
568
+ function assertSafeArgs(subcommand, args) {
569
+ const allowed = FLAGS_BY_CMD[subcommand];
570
+ let expectingValue = null;
571
+ for (const arg of args) {
572
+ if (isUnsafeArg(arg)) {
573
+ throw new ExecCliError(`rejected argument: ${JSON.stringify(arg)}`);
574
+ }
575
+ if (expectingValue) {
576
+ if (arg.startsWith("-")) {
577
+ throw new ExecCliError(`${expectingValue} requires a value`);
578
+ }
579
+ expectingValue = null;
580
+ continue;
581
+ }
582
+ if (!arg.startsWith("--") || !allowed.has(arg)) {
583
+ throw new ExecCliError(`flag not allowed for ${subcommand}: ${JSON.stringify(arg)}`);
584
+ }
585
+ if (VALUE_FLAGS.has(arg)) {
586
+ expectingValue = arg;
587
+ } else if (!BOOL_FLAGS.has(arg)) {
588
+ throw new ExecCliError(`flag not allowed for ${subcommand}: ${JSON.stringify(arg)}`);
589
+ }
590
+ }
591
+ if (expectingValue) {
592
+ throw new ExecCliError(`${expectingValue} requires a value`);
593
+ }
594
+ }
595
+ function killProcessGroup(child) {
596
+ const pid = child.pid;
597
+ if (pid && process.platform !== "win32") {
598
+ try {
599
+ process.kill(-pid, "SIGKILL");
600
+ return;
601
+ } catch {}
602
+ }
603
+ child.kill("SIGKILL");
604
+ }
605
+ async function execSecondlayer(subcommand, args, deps = {}) {
606
+ if (!ALLOWED.includes(subcommand)) {
607
+ throw new ExecCliError(`subcommand not allowed: ${subcommand}`);
608
+ }
609
+ assertSafeArgs(subcommand, args);
610
+ const argv = [subcommand, ...args];
611
+ if (subcommand === "setup") {
612
+ if (!argv.includes("--yes"))
613
+ argv.push("--yes");
614
+ } else if (!argv.includes("--json")) {
615
+ argv.push("--json");
616
+ }
617
+ const env = deps.env ?? process.env;
618
+ const bin = env.SECONDLAYER_BIN || "secondlayer";
619
+ const cwd = deps.cwd ?? env.SECONDLAYER_CWD ?? process.cwd();
620
+ const spawnFn = deps.spawn ?? spawn;
621
+ const timeout = deps.timeoutMs ?? TIMEOUT_MS[subcommand];
622
+ return new Promise((resolve) => {
623
+ let stdout = "";
624
+ let stderr = "";
625
+ let settled = false;
626
+ const child = spawnFn(bin, argv, {
627
+ cwd,
628
+ env,
629
+ stdio: ["ignore", "pipe", "pipe"],
630
+ detached: process.platform !== "win32",
631
+ shell: false
632
+ });
633
+ const timer = setTimeout(() => {
634
+ killProcessGroup(child);
635
+ finish({
636
+ code: 124,
637
+ stdout,
638
+ stderr: `${stderr}
639
+ timeout after ${timeout}ms`.trim()
640
+ });
641
+ }, timeout);
642
+ function finish(result) {
643
+ if (settled)
644
+ return;
645
+ settled = true;
646
+ clearTimeout(timer);
647
+ resolve(result);
648
+ }
649
+ child.stdout?.on("data", (chunk) => {
650
+ stdout += String(chunk);
651
+ });
652
+ child.stderr?.on("data", (chunk) => {
653
+ stderr += String(chunk);
654
+ });
655
+ child.on("error", (err) => {
656
+ finish({ code: 127, stdout, stderr: err.message });
657
+ });
658
+ child.on("close", (code) => {
659
+ finish({ code: code ?? 1, stdout, stderr });
660
+ });
661
+ });
662
+ }
663
+
664
+ // src/tools/setup.ts
665
+ function cliResponse(result) {
666
+ return jsonResponse(result, result.code !== 0);
667
+ }
668
+ function registerSetupTools(server, exec = execSecondlayer) {
669
+ defineTool(server, "setup", "Non-interactive self-host onboarding (secondlayer setup --yes). If the index is empty, this or archive_bootstrap fills it. Bootstrap is metered against the official archive. After it returns, poll instance_status until index.decoders are ok, then archive_verify, then codegen_index_schema. Do not download parquet.", {
670
+ network: z7.enum(["mainnet", "testnet", "devnet"]).describe("Stacks network"),
671
+ nodeMode: z7.enum(["external", "stacks", "full"]).describe("Node mode: external, stacks, or full"),
672
+ against: z7.string().optional().describe("Archive manifest URL"),
673
+ dir: z7.string().optional().describe("Compose project directory"),
674
+ skipBootstrap: z7.boolean().optional().describe("Sync from genesis instead of restoring an archive")
675
+ }, async ({ network, nodeMode, against, dir, skipBootstrap }) => {
676
+ const args = ["--yes", "--network", network, "--node-mode", nodeMode];
677
+ if (against !== undefined)
678
+ args.push("--against", against);
679
+ if (dir !== undefined)
680
+ args.push("--dir", dir);
681
+ if (skipBootstrap)
682
+ args.push("--skip-bootstrap");
683
+ return cliResponse(await exec("setup", args));
684
+ });
685
+ defineTool(server, "archive_bootstrap", "Restore verified history into this instance (secondlayer bootstrap --against … --yes --json). Metered against the official archive; quote happens inside the CLI. After bootstrap, poll instance_status until decoders ok, then archive_verify, then codegen_index_schema. Do not download parquet.", {
686
+ against: z7.string().describe("Archive manifest URL"),
687
+ fromBlock: z7.number().int().nonnegative().optional().describe("Restore from this height instead of genesis"),
688
+ toBlock: z7.number().int().nonnegative().optional().describe("Stop at this height instead of the archive tip")
689
+ }, async ({ against, fromBlock, toBlock }) => {
690
+ const args = ["--against", against, "--yes", "--json"];
691
+ if (fromBlock !== undefined)
692
+ args.push("--from-block", String(fromBlock));
693
+ if (toBlock !== undefined)
694
+ args.push("--to-block", String(toBlock));
695
+ return cliResponse(await exec("bootstrap", args));
696
+ });
697
+ defineTool(server, "archive_repair", "Plan (default) or apply a repair of local chain data against a signed archive. Metered when apply fetches from the official archive. After apply, poll instance_status until decoders ok, then archive_verify. Do not download parquet.", {
698
+ against: z7.string().describe("Archive manifest URL"),
699
+ apply: z7.boolean().optional().describe("Write the repair (default plan-only)"),
700
+ fromBlock: z7.number().int().nonnegative().optional().describe("First height to consider"),
701
+ toBlock: z7.number().int().nonnegative().optional().describe("Last height to consider")
702
+ }, async ({ against, apply, fromBlock, toBlock }) => {
703
+ const args = ["--against", against, "--json"];
704
+ if (apply)
705
+ args.push("--apply", "--yes");
706
+ if (fromBlock !== undefined)
707
+ args.push("--from-block", String(fromBlock));
708
+ if (toBlock !== undefined)
709
+ args.push("--to-block", String(toBlock));
710
+ return cliResponse(await exec("repair", args));
711
+ });
712
+ }
713
+
430
714
  // src/tools/streams.ts
431
715
  import { STREAMS_EVENT_TYPES } from "@secondlayer/shared";
432
- import { z as z6 } from "zod";
433
- var filterValue = z6.union([z6.string(), z6.array(z6.string())]);
716
+ import { z as z8 } from "zod";
717
+ var filterValue = z8.union([z8.string(), z8.array(z8.string())]);
434
718
  function registerStreamsTools(server, clientProvider = getClient) {
435
719
  defineTool(server, "streams_tip", "Current canonical chain tip as Streams sees it: block height/hash, burn height, finalized_height, lag_seconds, and the oldest seekable height/cursor for this key's retention window. Call it before a cursor walk to know where the stream ends, and after an ingest to check lag.", {}, async () => jsonResponse(await clientProvider().streams.tip()));
436
720
  defineTool(server, "streams_events", "List raw chain events from Streams — ONE page per call, newest filters applied server-side. Returns { events, next_cursor, tip, reorgs }. To follow the chain live, poll this tool with `cursor` set to the previous response's `next_cursor` (input is exclusive, so no duplicates); there is no open-stream tool because a tool call cannot hold a connection. ALWAYS narrow with types/contractId/sender/recipient — an unfiltered page is the full firehose.", {
437
- cursor: z6.string().optional().describe("Resume strictly after this cursor (`<block_height>:<event_index>`, e.g. 951475:3) — pass a prior response's next_cursor"),
438
- fromHeight: z6.number().int().nonnegative().optional().describe("Start block height (inclusive)"),
439
- toHeight: z6.number().int().nonnegative().optional().describe("End block height (inclusive)"),
440
- types: z6.array(z6.enum(STREAMS_EVENT_TYPES)).optional().describe("Event types to include"),
441
- notTypes: z6.array(z6.enum(STREAMS_EVENT_TYPES)).optional().describe("Event types to exclude (applied after types)"),
721
+ cursor: z8.string().optional().describe("Resume strictly after this cursor (`<block_height>:<event_index>`, e.g. 951475:3) — pass a prior response's next_cursor"),
722
+ fromHeight: z8.number().int().nonnegative().optional().describe("Start block height (inclusive)"),
723
+ toHeight: z8.number().int().nonnegative().optional().describe("End block height (inclusive)"),
724
+ types: z8.array(z8.enum(STREAMS_EVENT_TYPES)).optional().describe("Event types to include"),
725
+ notTypes: z8.array(z8.enum(STREAMS_EVENT_TYPES)).optional().describe("Event types to exclude (applied after types)"),
442
726
  contractId: filterValue.optional().describe("Contract id, or a list of contract ids to OR together"),
443
727
  sender: filterValue.optional().describe("Sender principal, or a list to OR together"),
444
728
  recipient: filterValue.optional().describe("Recipient principal, or a list to OR together"),
445
- assetIdentifier: z6.string().optional().describe("Asset identifier (contract::asset), e.g. SP…sbtc-token::sbtc-token"),
446
- limit: z6.number().int().min(1).max(1000).optional().describe("Page size, 1–1000 (default 100)")
729
+ assetIdentifier: z8.string().optional().describe("Asset identifier (contract::asset), e.g. SP…sbtc-token::sbtc-token"),
730
+ limit: z8.number().int().min(1).max(1000).optional().describe("Page size, 1–1000 (default 100)")
447
731
  }, async (params) => jsonResponse(await clientProvider().streams.events.list(params)));
448
732
  defineTool(server, "streams_events_by_tx", "List every event emitted by a single transaction, in emission order. Use it to explain one transaction end to end after finding it in streams_events or the Index.", {
449
- txId: z6.string().describe("Transaction id (0x-prefixed)")
733
+ txId: z8.string().describe("Transaction id (0x-prefixed)")
450
734
  }, async ({ txId }) => jsonResponse(await clientProvider().streams.events.byTxId(txId)));
451
735
  defineTool(server, "streams_block_events", "List every event in one block, addressed by block height or block hash. Use it to audit a block a consumer flagged, or to diff what a reorg replaced.", {
452
- heightOrHash: z6.union([z6.number().int().nonnegative(), z6.string()]).describe("Block height (number) or block hash (0x-prefixed string)")
736
+ heightOrHash: z8.union([z8.number().int().nonnegative(), z8.string()]).describe("Block height (number) or block hash (0x-prefixed string)")
453
737
  }, async ({ heightOrHash }) => jsonResponse(await clientProvider().streams.blocks.events(heightOrHash)));
454
738
  defineTool(server, "streams_canonical", "Get the canonical block at a height: hash, burn block hash, parent, and whether the height is still canonical. Use it to confirm a height you already consumed was not reorged away before you trust derived state.", {
455
- height: z6.number().int().nonnegative().describe("Block height")
739
+ height: z8.number().int().nonnegative().describe("Block height")
456
740
  }, async ({ height }) => jsonResponse(await clientProvider().streams.canonical(height)));
457
741
  defineTool(server, "streams_reorgs", "List reorgs detected since a point in time, newest last, with the new canonical tip for each. Returns { reorgs, next_since } — resume with next_since. Call it when a consumer's derived state disagrees with streams_canonical, or on a schedule to know which heights to reprocess.", {
458
- since: z6.string().describe("Required. ISO 8601 timestamp, or a `next_since` resume token from a prior response"),
459
- limit: z6.number().int().positive().optional().describe("Max reorgs to return")
742
+ since: z8.string().describe("Required. ISO 8601 timestamp, or a `next_since` resume token from a prior response"),
743
+ limit: z8.number().int().positive().optional().describe("Max reorgs to return")
460
744
  }, async ({ since, limit }) => jsonResponse(await clientProvider().streams.reorgs.list({
461
745
  since,
462
746
  ...limit !== undefined ? { limit } : {}
@@ -466,19 +750,19 @@ function registerStreamsTools(server, clientProvider = getClient) {
466
750
 
467
751
  // src/tools/subgraphs.ts
468
752
  import { bundleSubgraphCode } from "@secondlayer/bundler";
469
- import { z as z7 } from "zod";
753
+ import { z as z9 } from "zod";
470
754
  function registerSubgraphTools(server, clientProvider = getClient) {
471
755
  defineTool(server, "subgraphs_list", "List all deployed subgraphs. Returns summary fields only; read rows with subgraphs_query.", {}, async () => {
472
756
  const { data } = await clientProvider().subgraphs.list();
473
757
  return jsonResponse(data.map(formatSubgraphSummary));
474
758
  });
475
- defineTool(server, "subgraphs_status", "Get full details of a subgraph including schema, health, and table columns.", { name: z7.string().describe("Subgraph name") }, async ({ name }) => {
759
+ defineTool(server, "subgraphs_status", "Get full details of a subgraph including schema, health, and table columns.", { name: z9.string().describe("Subgraph name") }, async ({ name }) => {
476
760
  const detail = await clientProvider().subgraphs.status(name);
477
761
  return jsonResponse(detail);
478
762
  });
479
763
  defineTool(server, "subgraphs_spec", "Fetch a subgraph's self-describing spec — the tables, columns, filters, and read URLs a consumer needs, without guessing. `agent` (default) returns the compact JSON schema built for tool use, `openapi` the OpenAPI document for the subgraph's read routes, `markdown` human-readable docs. Read it before writing queries against an unfamiliar subgraph.", {
480
- name: z7.string().describe("Subgraph name"),
481
- format: z7.enum(["agent", "openapi", "markdown"]).optional().describe("agent = JSON schema for tool use (default), openapi = OpenAPI JSON, markdown = docs.md")
764
+ name: z9.string().describe("Subgraph name"),
765
+ format: z9.enum(["agent", "openapi", "markdown"]).optional().describe("agent = JSON schema for tool use (default), openapi = OpenAPI JSON, markdown = docs.md")
482
766
  }, async ({ name, format }) => {
483
767
  const client = clientProvider();
484
768
  if (format === "openapi")
@@ -488,15 +772,15 @@ function registerSubgraphTools(server, clientProvider = getClient) {
488
772
  return jsonResponse(await client.subgraphs.schema(name));
489
773
  });
490
774
  defineTool(server, "subgraphs_query", 'Query rows from a subgraph table (max 200 rows). Filters support operators: "amount.gte": "1000", "sender.neq": "SP...", "name.like": "%token%". Available operators: eq, neq, gt, gte, lt, lte, like. To TAIL new rows (no streaming over MCP): sort=_id, order=desc for the latest, then poll forward with the filter {"_id.gt": "<last _id seen>"}, order=asc — when tailing with a `fields` list, include "_id" in it or the next poll filter cannot be formed. Fetch one row by id with {"_id": "<id>"}. The same rows are readable over HTTP at GET /v1/subgraphs/<name>/<table> — { rows, next_cursor, tip } envelope, resume with ?cursor=<next_cursor> + _order=asc|desc (no _offset/_sort on /v1); hand that URL to third parties.', {
491
- name: z7.string().describe("Subgraph name"),
492
- table: z7.string().describe("Table name"),
493
- filters: z7.record(z7.string(), z7.string()).optional().describe('Column filters — plain values or with operators (e.g. {"amount.gte": "1000", "sender": "SP..."})'),
494
- sort: z7.string().optional().describe("Column to sort by"),
495
- order: z7.enum(["asc", "desc"]).optional().describe("Sort order"),
496
- limit: z7.number().max(200).optional().describe("Max rows (default 50, max 200)"),
497
- offset: z7.number().optional().describe("Offset for pagination"),
498
- fields: z7.string().optional().describe('Comma-separated column list to return (e.g. "sender,amount")'),
499
- count: z7.boolean().optional().describe("If true, return row count instead of rows")
775
+ name: z9.string().describe("Subgraph name"),
776
+ table: z9.string().describe("Table name"),
777
+ filters: z9.record(z9.string(), z9.string()).optional().describe('Column filters — plain values or with operators (e.g. {"amount.gte": "1000", "sender": "SP..."})'),
778
+ sort: z9.string().optional().describe("Column to sort by"),
779
+ order: z9.enum(["asc", "desc"]).optional().describe("Sort order"),
780
+ limit: z9.number().max(200).optional().describe("Max rows (default 50, max 200)"),
781
+ offset: z9.number().optional().describe("Offset for pagination"),
782
+ fields: z9.string().optional().describe('Comma-separated column list to return (e.g. "sender,amount")'),
783
+ count: z9.boolean().optional().describe("If true, return row count instead of rows")
500
784
  }, async ({
501
785
  name,
502
786
  table,
@@ -524,15 +808,15 @@ function registerSubgraphTools(server, clientProvider = getClient) {
524
808
  return jsonResponse(result);
525
809
  });
526
810
  defineTool(server, "subgraphs_reindex", "Reindex a subgraph: drops and rebuilds the whole subgraph from its start block to chain tip. Takes no block range — use subgraphs_backfill to process a specific range. Returns an operationId — check subgraphs_status (health) or the REST operations endpoint to track progress to completion.", {
527
- name: z7.string().describe("Subgraph name")
811
+ name: z9.string().describe("Subgraph name")
528
812
  }, async ({ name }) => {
529
813
  const result = await clientProvider().subgraphs.reindex(name);
530
814
  return jsonResponse(result);
531
815
  });
532
816
  defineTool(server, "subgraphs_backfill", "Backfill a subgraph over a block range. Non-destructive forward fill (does not drop existing data) — unlike subgraphs_reindex, and the only data-fill path for BYO subgraphs (reindex is blocked there). Both blocks required. Returns an operationId — check subgraphs_status (health) or the REST operations endpoint to track progress.", {
533
- name: z7.string().describe("Subgraph name"),
534
- fromBlock: z7.number().int().nonnegative().describe("Start block (inclusive)"),
535
- toBlock: z7.number().int().nonnegative().describe("End block (inclusive)")
817
+ name: z9.string().describe("Subgraph name"),
818
+ fromBlock: z9.number().int().nonnegative().describe("Start block (inclusive)"),
819
+ toBlock: z9.number().int().nonnegative().describe("End block (inclusive)")
536
820
  }, async ({ name, fromBlock, toBlock }) => {
537
821
  const result = await clientProvider().subgraphs.backfill(name, {
538
822
  fromBlock,
@@ -540,15 +824,15 @@ function registerSubgraphTools(server, clientProvider = getClient) {
540
824
  });
541
825
  return jsonResponse(result);
542
826
  });
543
- defineTool(server, "subgraphs_stop", "Cancel an in-flight reindex or backfill operation for a subgraph. Returns the stop request status; check subgraphs_status (health) or the REST operations endpoint to confirm it reaches a terminal state.", { name: z7.string().describe("Subgraph name") }, async ({ name }) => {
827
+ defineTool(server, "subgraphs_stop", "Cancel an in-flight reindex or backfill operation for a subgraph. Returns the stop request status; check subgraphs_status (health) or the REST operations endpoint to confirm it reaches a terminal state.", { name: z9.string().describe("Subgraph name") }, async ({ name }) => {
544
828
  const result = await clientProvider().subgraphs.stop(name);
545
829
  return jsonResponse(result);
546
830
  });
547
831
  defineTool(server, "subgraphs_gaps", "List indexing gaps (missing block ranges) for a subgraph. Each gap reports start/end/size, reason, and detected/resolved timestamps. Feed an unresolved gap's range into subgraphs_backfill to fill it. Defaults to unresolved gaps.", {
548
- name: z7.string().describe("Subgraph name"),
549
- limit: z7.number().int().positive().optional().describe("Max gaps to return"),
550
- offset: z7.number().int().nonnegative().optional().describe("Pagination offset"),
551
- resolved: z7.boolean().optional().describe("Filter by resolved state (omit for unresolved only)")
832
+ name: z9.string().describe("Subgraph name"),
833
+ limit: z9.number().int().positive().optional().describe("Max gaps to return"),
834
+ offset: z9.number().int().nonnegative().optional().describe("Pagination offset"),
835
+ resolved: z9.boolean().optional().describe("Filter by resolved state (omit for unresolved only)")
552
836
  }, async ({ name, limit, offset, resolved }) => {
553
837
  const result = await clientProvider().subgraphs.gaps(name, {
554
838
  limit,
@@ -558,20 +842,20 @@ function registerSubgraphTools(server, clientProvider = getClient) {
558
842
  return jsonResponse(result);
559
843
  });
560
844
  defineTool(server, "subgraphs_operations", "Operation history for a subgraph (deploy/reindex/backfill/stop), newest first — status, block range, progress, and error. THIS IS THE VERIFY CALL: after subgraphs_deploy, subgraphs_reindex, subgraphs_backfill, or subgraphs_stop, poll it with the returned operationId until `status` is terminal (completed/failed/cancelled) before reporting success. Omit operationId for the recent history.", {
561
- name: z7.string().describe("Subgraph name"),
562
- operationId: z7.string().optional().describe("Fetch one operation by id (the operationId returned by reindex/backfill/stop); omit for recent history")
845
+ name: z9.string().describe("Subgraph name"),
846
+ operationId: z9.string().optional().describe("Fetch one operation by id (the operationId returned by reindex/backfill/stop); omit for recent history")
563
847
  }, async ({ name, operationId }) => {
564
848
  const client = clientProvider();
565
849
  return jsonResponse(operationId ? await client.subgraphs.getOperation(name, operationId) : await client.subgraphs.operations(name));
566
850
  });
567
- defineTool(server, "subgraphs_delete", "Delete a subgraph permanently.", { name: z7.string().describe("Subgraph name") }, async ({ name }) => {
851
+ defineTool(server, "subgraphs_delete", "Delete a subgraph permanently.", { name: z9.string().describe("Subgraph name") }, async ({ name }) => {
568
852
  const result = await clientProvider().subgraphs.delete(name);
569
853
  return textResponse(result.message);
570
854
  });
571
855
  defineTool(server, "subgraphs_deploy", "Deploy a subgraph from TypeScript code. Pass the full defineSubgraph() source — it will be bundled, validated, and deployed. Optional startBlock overrides the source definition for this deploy. Set dryRun to validate and preview the schema/DDL without writing anything. Call `subgraphs_reindex` separately if you need a forced reindex.", {
572
- code: z7.string().describe("TypeScript source code containing a defineSubgraph() call"),
573
- startBlock: z7.number().int().nonnegative().optional().describe("Override the definition startBlock for this deploy"),
574
- dryRun: z7.boolean().optional().describe("Validate and preview the deploy (schema/DDL) without writing changes")
856
+ code: z9.string().describe("TypeScript source code containing a defineSubgraph() call"),
857
+ startBlock: z9.number().int().nonnegative().optional().describe("Override the definition startBlock for this deploy"),
858
+ dryRun: z9.boolean().optional().describe("Validate and preview the deploy (schema/DDL) without writing changes")
575
859
  }, async ({ code, startBlock, dryRun }) => {
576
860
  const bundled = await bundleSubgraphCode(code);
577
861
  const result = await clientProvider().subgraphs.deploy({
@@ -591,38 +875,38 @@ function registerSubgraphTools(server, clientProvider = getClient) {
591
875
 
592
876
  // src/tools/subscriptions.ts
593
877
  import { CHAIN_TRIGGER_TYPES } from "@secondlayer/shared";
594
- import { z as z8 } from "zod";
878
+ import { z as z10 } from "zod";
595
879
  function registerSubscriptionTools(server, clientProvider = getClient) {
596
880
  defineTool(server, "subscriptions_list", "List all subscriptions for the current account. Returns summary fields (no secrets).", {}, async () => {
597
881
  const { data } = await clientProvider().subscriptions.list();
598
882
  return jsonResponse(data);
599
883
  });
600
- defineTool(server, "subscriptions_get", "Get full detail for a subscription (filter, auth, retry config, circuit state).", { id: z8.string().describe("Subscription id") }, async ({ id }) => {
884
+ defineTool(server, "subscriptions_get", "Get full detail for a subscription (filter, auth, retry config, circuit state).", { id: z10.string().describe("Subscription id") }, async ({ id }) => {
601
885
  const detail = await clientProvider().subscriptions.get(id);
602
886
  return jsonResponse(detail);
603
887
  });
604
888
  defineTool(server, "subscriptions_create", "Create a subscription. Two kinds (mutually exclusive): a SUBGRAPH subscription fires on a subgraph table's rows (set subgraphName + tableName + optional filter); a CHAIN subscription fires on raw chain events with no subgraph (set triggers). Returns `signingSecret` ONCE — forward it to the user so they can wire it into their receiver.", {
605
- name: z8.string().describe("Human-readable name, unique per account"),
606
- subgraphName: z8.string().optional().describe("Subgraph to subscribe to (subgraph subscription)"),
607
- tableName: z8.string().optional().describe("Table within the subgraph (subgraph subscription)"),
608
- triggers: z8.array(z8.object({
609
- type: z8.enum(CHAIN_TRIGGER_TYPES),
610
- contractId: z8.string().optional(),
611
- functionName: z8.string().optional(),
612
- caller: z8.string().optional(),
613
- sender: z8.string().optional(),
614
- recipient: z8.string().optional(),
615
- assetIdentifier: z8.string().optional(),
616
- deployer: z8.string().optional(),
617
- contractName: z8.string().optional(),
618
- topic: z8.string().optional(),
619
- lockedAddress: z8.string().optional(),
620
- trait: z8.string().optional(),
621
- minAmount: z8.union([z8.string(), z8.number()]).optional(),
622
- maxAmount: z8.union([z8.string(), z8.number()]).optional()
889
+ name: z10.string().describe("Human-readable name, unique per account"),
890
+ subgraphName: z10.string().optional().describe("Subgraph to subscribe to (subgraph subscription)"),
891
+ tableName: z10.string().optional().describe("Table within the subgraph (subgraph subscription)"),
892
+ triggers: z10.array(z10.object({
893
+ type: z10.enum(CHAIN_TRIGGER_TYPES),
894
+ contractId: z10.string().optional(),
895
+ functionName: z10.string().optional(),
896
+ caller: z10.string().optional(),
897
+ sender: z10.string().optional(),
898
+ recipient: z10.string().optional(),
899
+ assetIdentifier: z10.string().optional(),
900
+ deployer: z10.string().optional(),
901
+ contractName: z10.string().optional(),
902
+ topic: z10.string().optional(),
903
+ lockedAddress: z10.string().optional(),
904
+ trait: z10.string().optional(),
905
+ minAmount: z10.union([z10.string(), z10.number()]).optional(),
906
+ maxAmount: z10.union([z10.string(), z10.number()]).optional()
623
907
  })).optional().describe("Chain triggers (chain subscription) — provide INSTEAD of subgraphName/tableName. Each targets a raw chain event/tx; string fields accept `*` wildcards, `trait` scopes to a SIP/trait. Per-type accepted fields: see the secondlayer://chain-triggers resource. Forward-looking: starts at chain tip, no backfill."),
624
- url: z8.string().describe("Webhook URL"),
625
- format: z8.enum([
908
+ url: z10.string().describe("Webhook URL"),
909
+ format: z10.enum([
626
910
  "standard-webhooks",
627
911
  "inngest",
628
912
  "trigger",
@@ -630,20 +914,20 @@ function registerSubscriptionTools(server, clientProvider = getClient) {
630
914
  "cloudevents",
631
915
  "raw"
632
916
  ]).optional().describe("Wire format (default standard-webhooks)"),
633
- runtime: z8.enum(["inngest", "trigger", "cloudflare", "node"]).optional().describe("Receiver runtime label (display only)"),
634
- filter: z8.record(z8.string(), z8.unknown()).optional().describe('Scalar filter DSL, e.g. {"amount": {"gte": 100}, "sender": "SP..."}'),
635
- authConfig: z8.record(z8.string(), z8.unknown()).optional().describe('Receiver auth sent with each delivery, e.g. {"type": "bearer", "token": "..."}')
917
+ runtime: z10.enum(["inngest", "trigger", "cloudflare", "node"]).optional().describe("Receiver runtime label (display only)"),
918
+ filter: z10.record(z10.string(), z10.unknown()).optional().describe('Scalar filter DSL, e.g. {"amount": {"gte": 100}, "sender": "SP..."}'),
919
+ authConfig: z10.record(z10.string(), z10.unknown()).optional().describe('Receiver auth sent with each delivery, e.g. {"type": "bearer", "token": "..."}')
636
920
  }, async (input) => {
637
921
  const res = await clientProvider().subscriptions.create(input);
638
922
  return jsonResponse(res);
639
923
  });
640
924
  defineTool(server, "subscriptions_update", "Patch a subscription (name, url, filter, authConfig, format, runtime, retry, timeout, concurrency).", {
641
- id: z8.string(),
642
- name: z8.string().optional().describe("Rename the subscription"),
643
- url: z8.string().optional(),
644
- filter: z8.record(z8.string(), z8.unknown()).optional(),
645
- authConfig: z8.record(z8.string(), z8.unknown()).optional().describe("Receiver auth sent with each delivery (bearer/etc.)"),
646
- format: z8.enum([
925
+ id: z10.string(),
926
+ name: z10.string().optional().describe("Rename the subscription"),
927
+ url: z10.string().optional(),
928
+ filter: z10.record(z10.string(), z10.unknown()).optional(),
929
+ authConfig: z10.record(z10.string(), z10.unknown()).optional().describe("Receiver auth sent with each delivery (bearer/etc.)"),
930
+ format: z10.enum([
647
931
  "standard-webhooks",
648
932
  "inngest",
649
933
  "trigger",
@@ -651,36 +935,36 @@ function registerSubscriptionTools(server, clientProvider = getClient) {
651
935
  "cloudevents",
652
936
  "raw"
653
937
  ]).optional(),
654
- runtime: z8.enum(["inngest", "trigger", "cloudflare", "node"]).nullable().optional(),
655
- maxRetries: z8.number().int().min(0).optional(),
656
- timeoutMs: z8.number().int().min(100).optional(),
657
- concurrency: z8.number().int().min(1).optional()
938
+ runtime: z10.enum(["inngest", "trigger", "cloudflare", "node"]).nullable().optional(),
939
+ maxRetries: z10.number().int().min(0).optional(),
940
+ timeoutMs: z10.number().int().min(100).optional(),
941
+ concurrency: z10.number().int().min(1).optional()
658
942
  }, async ({ id, ...patch }) => {
659
943
  const res = await clientProvider().subscriptions.update(id, patch);
660
944
  return jsonResponse(res);
661
945
  });
662
- defineTool(server, "subscriptions_delete", "Delete a subscription. Pending outbox rows are cascade-deleted.", { id: z8.string() }, async ({ id }) => {
946
+ defineTool(server, "subscriptions_delete", "Delete a subscription. Pending outbox rows are cascade-deleted.", { id: z10.string() }, async ({ id }) => {
663
947
  const res = await clientProvider().subscriptions.delete(id);
664
948
  return jsonResponse(res);
665
949
  });
666
- defineTool(server, "subscriptions_test", "Send a one-off test webhook to a subscription's URL (built for its format, SSRF-guarded). Logged as a delivery row. Returns {ok, statusCode, error, durationMs, deliveryId}.", { id: z8.string().describe("Subscription id") }, async ({ id }) => {
950
+ defineTool(server, "subscriptions_test", "Send a one-off test webhook to a subscription's URL (built for its format, SSRF-guarded). Logged as a delivery row. Returns {ok, statusCode, error, durationMs, deliveryId}.", { id: z10.string().describe("Subscription id") }, async ({ id }) => {
667
951
  const res = await clientProvider().subscriptions.test(id);
668
952
  return jsonResponse(res);
669
953
  });
670
- defineTool(server, "subscriptions_pause", "Pause a subscription: stops delivery attempts and stops queueing new ones. Nothing is deleted — resume picks the subscription back up from the tip. Verify with subscriptions_get (status).", { id: z8.string().describe("Subscription id") }, async ({ id }) => jsonResponse(await clientProvider().subscriptions.pause(id)));
671
- defineTool(server, "subscriptions_resume", "Resume a paused subscription (also clears a tripped circuit breaker). Deliveries restart from the current tip — use subscriptions_replay for the blocks missed while paused. Verify with subscriptions_get (status).", { id: z8.string().describe("Subscription id") }, async ({ id }) => jsonResponse(await clientProvider().subscriptions.resume(id)));
672
- defineTool(server, "subscriptions_rotate_secret", "Rotate a subscription's webhook signing secret. Returns the NEW `signingSecret` ONCE — forward it to the user; deliveries signed with the old secret stop verifying as soon as this returns, so the receiver must be updated.", { id: z8.string().describe("Subscription id") }, async ({ id }) => jsonResponse(await clientProvider().subscriptions.rotateSecret(id)));
673
- defineTool(server, "subscriptions_deliveries", "List recent delivery attempts for a subscription — status code, attempt count, error, duration, timestamps. THIS IS THE VERIFY CALL: after subscriptions_create, subscriptions_test, or subscriptions_replay, read it to confirm the webhook actually landed (and to see the receiver's response when it didn't) instead of trusting the enqueue result.", { id: z8.string().describe("Subscription id") }, async ({ id }) => jsonResponse(await clientProvider().subscriptions.deliveries(id)));
674
- defineTool(server, "subscriptions_dead", "List a subscription's dead-letter queue — deliveries that exhausted their retries, with the outbox id, payload, and last error. Diagnose the receiver first (subscriptions_get for the URL/auth, subscriptions_test for a live probe), then requeue rows with subscriptions_requeue.", { id: z8.string().describe("Subscription id") }, async ({ id }) => jsonResponse(await clientProvider().subscriptions.dead(id)));
954
+ defineTool(server, "subscriptions_pause", "Pause a subscription: stops delivery attempts and stops queueing new ones. Nothing is deleted — resume picks the subscription back up from the tip. Verify with subscriptions_get (status).", { id: z10.string().describe("Subscription id") }, async ({ id }) => jsonResponse(await clientProvider().subscriptions.pause(id)));
955
+ defineTool(server, "subscriptions_resume", "Resume a paused subscription (also clears a tripped circuit breaker). Deliveries restart from the current tip — use subscriptions_replay for the blocks missed while paused. Verify with subscriptions_get (status).", { id: z10.string().describe("Subscription id") }, async ({ id }) => jsonResponse(await clientProvider().subscriptions.resume(id)));
956
+ defineTool(server, "subscriptions_rotate_secret", "Rotate a subscription's webhook signing secret. Returns the NEW `signingSecret` ONCE — forward it to the user; deliveries signed with the old secret stop verifying as soon as this returns, so the receiver must be updated.", { id: z10.string().describe("Subscription id") }, async ({ id }) => jsonResponse(await clientProvider().subscriptions.rotateSecret(id)));
957
+ defineTool(server, "subscriptions_deliveries", "List recent delivery attempts for a subscription — status code, attempt count, error, duration, timestamps. THIS IS THE VERIFY CALL: after subscriptions_create, subscriptions_test, or subscriptions_replay, read it to confirm the webhook actually landed (and to see the receiver's response when it didn't) instead of trusting the enqueue result.", { id: z10.string().describe("Subscription id") }, async ({ id }) => jsonResponse(await clientProvider().subscriptions.deliveries(id)));
958
+ defineTool(server, "subscriptions_dead", "List a subscription's dead-letter queue — deliveries that exhausted their retries, with the outbox id, payload, and last error. Diagnose the receiver first (subscriptions_get for the URL/auth, subscriptions_test for a live probe), then requeue rows with subscriptions_requeue.", { id: z10.string().describe("Subscription id") }, async ({ id }) => jsonResponse(await clientProvider().subscriptions.dead(id)));
675
959
  defineTool(server, "subscriptions_requeue", "Requeue ONE dead-lettered delivery for another attempt, by its outbox id from subscriptions_dead. Fix the receiver first — a requeue against a still-broken endpoint just dies again. Verify with subscriptions_deliveries.", {
676
- id: z8.string().describe("Subscription id"),
677
- outboxId: z8.string().describe("Outbox id of the dead delivery (from subscriptions_dead)")
960
+ id: z10.string().describe("Subscription id"),
961
+ outboxId: z10.string().describe("Outbox id of the dead delivery (from subscriptions_dead)")
678
962
  }, async ({ id, outboxId }) => jsonResponse(await clientProvider().subscriptions.requeue(id, outboxId)));
679
963
  defineTool(server, "subscriptions_replay", "Replay a block range for a subscription. Replays run at 10% of batch capacity — use sparingly. Pass `force` (a short idempotency suffix) to re-run a range that was already replayed.", {
680
- id: z8.string(),
681
- fromBlock: z8.number().int().nonnegative(),
682
- toBlock: z8.number().int().nonnegative(),
683
- force: z8.string().optional().describe("Idempotency suffix to force a duplicate replay of the range")
964
+ id: z10.string(),
965
+ fromBlock: z10.number().int().nonnegative(),
966
+ toBlock: z10.number().int().nonnegative(),
967
+ force: z10.string().optional().describe("Idempotency suffix to force a duplicate replay of the range")
684
968
  }, async ({ id, fromBlock, toBlock, force }) => {
685
969
  const res = await clientProvider().subscriptions.replay(id, {
686
970
  fromBlock,
@@ -706,6 +990,9 @@ function createServer() {
706
990
  registerStreamsTools(server);
707
991
  registerContractTools(server);
708
992
  registerCodegenTools(server);
993
+ registerInstanceTools(server);
994
+ registerArchiveTools(server);
995
+ registerSetupTools(server);
709
996
  const baseUrl = process.env.SECONDLAYER_API_URL || process.env.SL_API_URL || "http://127.0.0.1:3800";
710
997
  if (isHostedArchiveUrl(baseUrl)) {
711
998
  registerAccountTools(server);
@@ -719,5 +1006,5 @@ var server = createServer();
719
1006
  var transport = new StdioServerTransport;
720
1007
  await server.connect(transport);
721
1008
 
722
- //# debugId=A32A9DB8FD9D2A0F64756E2164756E21
1009
+ //# debugId=1DDB49B11F03E33264756E2164756E21
723
1010
  //# sourceMappingURL=bin.js.map