@secondlayer/mcp 7.2.0 → 7.3.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,6 +21,7 @@ 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";
@@ -28,6 +29,8 @@ import { TYPE_MAP } from "@secondlayer/subgraphs/schema";
28
29
  // src/lib/client.ts
29
30
  import { SecondLayer, resolveApiKey } from "@secondlayer/sdk";
30
31
  var instance = null;
32
+ var HOSTED_KEY_HINT = "set SL_ARCHIVE_API_KEY (sk-sl_*) for credits; INSTANCE_TOKEN is the instance";
33
+ var DEFAULT_ARCHIVE_OPS_URL = "https://api.secondlayer.tools";
31
34
  function readApiKey() {
32
35
  return resolveApiKey();
33
36
  }
@@ -45,6 +48,22 @@ function getClient() {
45
48
  }
46
49
  return instance;
47
50
  }
51
+ function readArchiveApiKey() {
52
+ const key = process.env.SL_ARCHIVE_API_KEY;
53
+ return key && key.length > 0 ? key : undefined;
54
+ }
55
+ function getArchiveOpsClient() {
56
+ const apiKey = readArchiveApiKey();
57
+ if (!apiKey) {
58
+ throw new Error(HOSTED_KEY_HINT);
59
+ }
60
+ const archiveOpsUrl = process.env.SL_CREDITS_API_URL || process.env.ARCHIVE_OPS_API_URL || DEFAULT_ARCHIVE_OPS_URL;
61
+ return new SecondLayer({
62
+ apiKey,
63
+ origin: "mcp",
64
+ archiveOpsUrl
65
+ });
66
+ }
48
67
  var keyHint = " — set INSTANCE_TOKEN from `sl init` for writes (SL_API_KEY is a legacy alias)";
49
68
  async function apiRequest(method, path, body) {
50
69
  const apiKey = readApiKey();
@@ -158,7 +177,11 @@ var PRODUCT_BLURBS = {
158
177
  subgraphs: "author/scaffold/deploy/query custom indexes",
159
178
  subscriptions: "webhook delivery on subgraph rows or raw chain events",
160
179
  account: "identity and self-provisioned API keys",
161
- codegen: "ORM schemas for the tables you read"
180
+ codegen: "ORM schemas for the tables you read",
181
+ instance: "decoder health and empty-index diagnosis",
182
+ archive: "signed archive verify, bootstrap/repair, quote, latest pointer",
183
+ setup: "one-command self-host onboarding",
184
+ credits: "archive credits balance at api.secondlayer.tools"
162
185
  };
163
186
  var PRODUCT_ORDER = [
164
187
  "index",
@@ -167,12 +190,17 @@ var PRODUCT_ORDER = [
167
190
  "subgraphs",
168
191
  "subscriptions",
169
192
  "account",
170
- "codegen"
193
+ "codegen",
194
+ "instance",
195
+ "archive",
196
+ "setup",
197
+ "credits"
171
198
  ];
172
199
  function buildCapabilities() {
173
200
  const byPrefix = new Map;
174
201
  for (const name of getRegisteredToolNames()) {
175
- const prefix = name.slice(0, name.indexOf("_"));
202
+ const sep = name.indexOf("_");
203
+ const prefix = sep === -1 ? name : name.slice(0, sep);
176
204
  const tools = byPrefix.get(prefix) ?? [];
177
205
  tools.push(name);
178
206
  byPrefix.set(prefix, tools);
@@ -206,6 +234,7 @@ async function buildContext(deps = { clientProvider: getClient }) {
206
234
  return field.error ? `unavailable: ${field.error.message}` : unavailable;
207
235
  };
208
236
  const snap = await deps.clientProvider().context().catch(() => null);
237
+ const instance2 = snap?.instance?.value ? snap.instance.value : orNull(snap?.instance);
209
238
  return {
210
239
  authState: {
211
240
  apiKeySet: Boolean(readApiKey())
@@ -216,10 +245,12 @@ async function buildContext(deps = { clientProvider: getClient }) {
216
245
  indexTip: orNull(snap?.indexTip),
217
246
  subgraphs: snap?.subgraphs.value ? snap.subgraphs.value.map(formatSubgraphSummary) : orNull(snap?.subgraphs),
218
247
  subscriptions: orNull(snap?.subscriptions),
219
- activeOperations: orNull(snap?.activeOperations)
248
+ activeOperations: orNull(snap?.activeOperations),
249
+ instance: instance2
220
250
  },
221
251
  whatYouCanDo: buildCapabilities(),
222
- readAuthTiers: READ_AUTH_TIERS
252
+ readAuthTiers: READ_AUTH_TIERS,
253
+ ...snap?.instance?.value?.state === "empty-index" ? { nextStep: BOOTSTRAP_STEP } : {}
223
254
  };
224
255
  }
225
256
  function registerResources(server) {
@@ -293,18 +324,43 @@ function registerAccountTools(server) {
293
324
  }, async ({ name }) => jsonResponse(await apiRequest("POST", "/api/keys", { name })));
294
325
  }
295
326
 
327
+ // src/tools/archive.ts
328
+ import { z as z2 } from "zod";
329
+ var FLOW = ["bootstrap", "repair"];
330
+ function registerArchiveTools(server, clientProvider = getClient, archiveOpsClientProvider = getArchiveOpsClient) {
331
+ 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.", {
332
+ against: z2.string().describe("Archive manifest URL"),
333
+ fromBlock: z2.number().int().nonnegative().optional().describe("First height (inclusive)"),
334
+ toBlock: z2.number().int().nonnegative().optional().describe("Last height (inclusive)"),
335
+ target: z2.string().optional().describe("Verify target (default raw)")
336
+ }, async ({ against, fromBlock, toBlock, target }) => jsonResponse(await clientProvider().archive.verify({
337
+ against,
338
+ fromBlock,
339
+ toBlock,
340
+ target
341
+ })));
342
+ defineTool(server, "archive_latest", "Signed pointer to the official archive tree (hosted). Needs SL_ARCHIVE_API_KEY (sk-sl_*), not INSTANCE_TOKEN. Use the returned origin as --against for archive_bootstrap. Do not download parquet.", {
343
+ against: z2.string().optional().describe("Override latest.json URL (default official tree)")
344
+ }, async ({ against }) => jsonResponse(await archiveOpsClientProvider().archive.latest(against)));
345
+ defineTool(server, "archive_quote", "Price a hosted archive fetch (metered). Needs SL_ARCHIVE_API_KEY (sk-sl_*), not INSTANCE_TOKEN. Quote happens here; bootstrap/repair also quote inside the CLI. Do not download parquet.", {
346
+ paths: z2.array(z2.string()).describe("Partition paths to price"),
347
+ flow: z2.enum(FLOW).describe("bootstrap or repair")
348
+ }, async ({ paths, flow }) => jsonResponse(await archiveOpsClientProvider().archive.quote({ paths, flow })));
349
+ defineTool(server, "credits_balance", "Archive credits balance at api.secondlayer.tools. Needs SL_ARCHIVE_API_KEY (sk-sl_*); INSTANCE_TOKEN is the instance.", {}, async () => jsonResponse(await archiveOpsClientProvider().archive.credits.balance()));
350
+ }
351
+
296
352
  // src/tools/codegen.ts
297
353
  import {
298
354
  generateIndexSchema
299
355
  } from "@secondlayer/subgraphs";
300
- import { z as z2 } from "zod";
356
+ import { z as z3 } from "zod";
301
357
  var TARGETS = ["prisma", "kysely", "drizzle", "json-schema"];
302
358
  function registerCodegenTools(server) {
303
359
  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)")
360
+ target: z3.enum(TARGETS).optional().describe("Output flavor (default kysely)"),
361
+ tables: z3.array(z3.string()).optional().describe("Restrict to these Index tables (default: all)"),
362
+ schemaName: z3.string().optional().describe("Postgres schema to qualify table names with"),
363
+ datasourceEnv: z3.string().optional().describe("Prisma only: datasource url env var (default DATABASE_URL)")
308
364
  }, ({ target, tables, schemaName, datasourceEnv }) => textResponse(generateIndexSchema(target ?? "kysely", {
309
365
  tables,
310
366
  schemaName,
@@ -313,17 +369,17 @@ function registerCodegenTools(server) {
313
369
  }
314
370
 
315
371
  // src/tools/contracts.ts
316
- import { z as z3 } from "zod";
372
+ import { z as z4 } from "zod";
317
373
  function registerContractTools(server, clientProvider = getClient) {
318
374
  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")
375
+ trait: z4.string().describe('Required. Trait to match (e.g. "sip-010").'),
376
+ conformance: z4.enum(["declared", "inferred", "any"]).optional().describe("declared = parsed from source, inferred = ABI shape-match, any = either (default)"),
377
+ include: z4.literal("abi").optional().describe(`Set to "abi" to include each contract's full ABI`),
378
+ limit: z4.number().optional().describe("Page size, 1–500 (default 100)"),
379
+ cursor: z4.string().optional().describe("Opaque cursor from a prior response's next_cursor")
324
380
  }, async (params) => jsonResponse(await clientProvider().contracts.list(params)));
325
381
  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)")
382
+ contractId: z4.string().describe("Fully qualified contract id (e.g. SP….amm-pool-v2-01)")
327
383
  }, async ({ contractId }) => {
328
384
  const contract = await clientProvider().contracts.get(contractId, {
329
385
  includeAbi: true
@@ -340,14 +396,14 @@ function registerContractTools(server, clientProvider = getClient) {
340
396
 
341
397
  // src/tools/index.ts
342
398
  import { DECODED_EVENT_TYPES } from "@secondlayer/shared";
343
- import { z as z4 } from "zod";
399
+ import { z as z5 } from "zod";
344
400
  var INDEX_EVENT_TYPES = DECODED_EVENT_TYPES;
345
401
  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")
402
+ contractId: z5.string().optional().describe("Filter by contract id"),
403
+ fromHeight: z5.number().optional().describe("Start block height (inclusive)"),
404
+ toHeight: z5.number().optional().describe("End block height (inclusive)"),
405
+ cursor: z5.string().optional().describe("Opaque cursor from a prior response's next_cursor"),
406
+ limit: z5.number().optional().describe("Max rows for this page")
351
407
  };
352
408
  var heightFilters = {
353
409
  fromHeight: rangeFilters.fromHeight,
@@ -358,52 +414,62 @@ var heightFilters = {
358
414
  function registerIndexTools(server, clientProvider = getClient) {
359
415
  defineTool(server, "index_ft_transfers", "List decoded SIP-010 fungible-token transfers from Index. Reads are keyless.", {
360
416
  ...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")
417
+ sender: z5.string().optional().describe("Filter by sender principal"),
418
+ recipient: z5.string().optional().describe("Filter by recipient principal"),
419
+ assetIdentifier: z5.string().optional().describe("Filter by asset identifier (contract::asset), e.g. SP…sbtc-token::sbtc-token")
364
420
  }, async (params) => jsonResponse(await clientProvider().index.ftTransfers.list(params)));
365
421
  defineTool(server, "index_nft_transfers", "List decoded SIP-009 non-fungible-token transfers from Index. Reads are keyless.", {
366
422
  ...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)")
423
+ sender: z5.string().optional().describe("Filter by sender principal"),
424
+ recipient: z5.string().optional().describe("Filter by recipient principal"),
425
+ assetIdentifier: z5.string().optional().describe("Filter by asset identifier (contract::asset)")
370
426
  }, async (params) => jsonResponse(await clientProvider().index.nftTransfers.list(params)));
371
427
  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."),
428
+ eventType: z5.enum(INDEX_EVENT_TYPES).describe("Required. Decoded event type to list."),
373
429
  ...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.")
430
+ sender: z5.string().optional().describe("Filter by sender principal"),
431
+ recipient: z5.string().optional().describe("Filter by recipient principal"),
432
+ assetIdentifier: z5.string().optional().describe("Filter by asset identifier where applicable"),
433
+ 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."),
434
+ 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
435
  }, async (params) => jsonResponse(await clientProvider().index.events.list(params)));
380
436
  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
437
  ...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.")
438
+ functionName: z5.string().optional().describe("Filter by called function name"),
439
+ sender: z5.string().optional().describe("Filter by caller principal"),
440
+ trait: z5.string().optional().describe("Match contracts conforming to a trait/standard (e.g. sip-010). Mutually exclusive with contractId.")
385
441
  }, async (params) => jsonResponse(await clientProvider().index.contractCalls.list(params)));
386
442
  defineTool(server, "index_blocks", "List decoded blocks from Index. Reads are keyless.", { ...heightFilters }, async (params) => jsonResponse(await clientProvider().index.blocks.list(params)));
387
443
  defineTool(server, "index_transactions", "List decoded transactions from Index. Filter by type, sender, or contract. Reads are keyless.", {
388
444
  ...rangeFilters,
389
- type: z4.string().optional().describe("Filter by transaction type"),
390
- sender: z4.string().optional().describe("Filter by sender principal")
445
+ type: z5.string().optional().describe("Filter by transaction type"),
446
+ sender: z5.string().optional().describe("Filter by sender principal")
391
447
  }, async (params) => jsonResponse(await clientProvider().index.transactions.list(params)));
392
448
  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")
449
+ contractId: z5.string().describe("Contract id (SP….name) whose print events to profile")
394
450
  }, async (params) => jsonResponse(await clientProvider().index.printSchema(params.contractId)));
395
451
  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
452
  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()
453
+ requests: z5.array(z5.object({
454
+ path: z5.string().describe("Public /v1 read path"),
455
+ params: z5.record(z5.string(), z5.string()).optional()
400
456
  })).min(1).max(10).describe("Read descriptors, executed concurrently")
401
457
  }, async (params) => jsonResponse(await clientProvider().batch(params.requests)));
402
458
  }
403
459
 
460
+ // src/tools/instance.ts
461
+ function registerInstanceTools(server, clientProvider = getClient) {
462
+ 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 () => {
463
+ const client = clientProvider();
464
+ const status = await client.instance.status();
465
+ const diagnosis = await client.instance.diagnose();
466
+ return jsonResponse({ status, diagnosis });
467
+ });
468
+ }
469
+
404
470
  // src/tools/scaffold.ts
405
471
  import { generateSubgraphCode } from "@secondlayer/scaffold";
406
- import { z as z5 } from "zod";
472
+ import { z as z6 } from "zod";
407
473
  async function fetchAbi(clientProvider, contractId) {
408
474
  const contract = await clientProvider().contracts.get(contractId, {
409
475
  includeAbi: true
@@ -418,8 +484,8 @@ async function fetchAbi(clientProvider, contractId) {
418
484
  }
419
485
  function registerScaffoldTools(server, clientProvider = getClient) {
420
486
  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)")
487
+ contractId: z6.string().describe("Fully qualified contract ID (e.g. SP102V8P0F7JX67ARQ77WEA3D3CFB5XW39REDT0AM.amm-pool-v2-01)"),
488
+ subgraphName: z6.string().optional().describe("Override the subgraph name (defaults to contract name)")
423
489
  }, async ({ contractId, subgraphName }) => {
424
490
  const { functions } = await fetchAbi(clientProvider, contractId);
425
491
  const code = generateSubgraphCode(contractId, functions, subgraphName);
@@ -427,36 +493,245 @@ function registerScaffoldTools(server, clientProvider = getClient) {
427
493
  });
428
494
  }
429
495
 
496
+ // src/tools/setup.ts
497
+ import { z as z7 } from "zod";
498
+
499
+ // src/lib/exec-cli.ts
500
+ import {
501
+ spawn
502
+ } from "node:child_process";
503
+ var ALLOWED = ["setup", "bootstrap", "repair", "verify"];
504
+ var TIMEOUT_MS = {
505
+ setup: 15 * 60 * 1000,
506
+ bootstrap: 10 * 60 * 1000,
507
+ repair: 10 * 60 * 1000,
508
+ verify: 2 * 60 * 1000
509
+ };
510
+ var VALUE_FLAGS = new Set([
511
+ "--against",
512
+ "--from-block",
513
+ "--to-block",
514
+ "--network",
515
+ "--node-mode",
516
+ "--dir"
517
+ ]);
518
+ var BOOL_FLAGS = new Set(["--yes", "--json", "--apply", "--skip-bootstrap"]);
519
+ var FLAGS_BY_CMD = {
520
+ setup: new Set([
521
+ "--yes",
522
+ "--network",
523
+ "--node-mode",
524
+ "--against",
525
+ "--dir",
526
+ "--skip-bootstrap"
527
+ ]),
528
+ bootstrap: new Set([
529
+ "--against",
530
+ "--yes",
531
+ "--json",
532
+ "--from-block",
533
+ "--to-block"
534
+ ]),
535
+ repair: new Set([
536
+ "--against",
537
+ "--json",
538
+ "--apply",
539
+ "--from-block",
540
+ "--to-block",
541
+ "--yes"
542
+ ]),
543
+ verify: new Set(["--against", "--json", "--from-block", "--to-block"])
544
+ };
545
+
546
+ class ExecCliError extends Error {
547
+ constructor(message) {
548
+ super(message);
549
+ this.name = "ExecCliError";
550
+ }
551
+ }
552
+ function isUnsafeArg(arg) {
553
+ if (arg.includes("\x00"))
554
+ return true;
555
+ if (/[\n\r]/.test(arg))
556
+ return true;
557
+ return /^[;|&]/.test(arg.trim());
558
+ }
559
+ function assertSafeArgs(subcommand, args) {
560
+ const allowed = FLAGS_BY_CMD[subcommand];
561
+ let expectingValue = null;
562
+ for (const arg of args) {
563
+ if (isUnsafeArg(arg)) {
564
+ throw new ExecCliError(`rejected argument: ${JSON.stringify(arg)}`);
565
+ }
566
+ if (expectingValue) {
567
+ if (arg.startsWith("-")) {
568
+ throw new ExecCliError(`${expectingValue} requires a value`);
569
+ }
570
+ expectingValue = null;
571
+ continue;
572
+ }
573
+ if (!arg.startsWith("--") || !allowed.has(arg)) {
574
+ throw new ExecCliError(`flag not allowed for ${subcommand}: ${JSON.stringify(arg)}`);
575
+ }
576
+ if (VALUE_FLAGS.has(arg)) {
577
+ expectingValue = arg;
578
+ } else if (!BOOL_FLAGS.has(arg)) {
579
+ throw new ExecCliError(`flag not allowed for ${subcommand}: ${JSON.stringify(arg)}`);
580
+ }
581
+ }
582
+ if (expectingValue) {
583
+ throw new ExecCliError(`${expectingValue} requires a value`);
584
+ }
585
+ }
586
+ function killProcessGroup(child) {
587
+ const pid = child.pid;
588
+ if (pid && process.platform !== "win32") {
589
+ try {
590
+ process.kill(-pid, "SIGKILL");
591
+ return;
592
+ } catch {}
593
+ }
594
+ child.kill("SIGKILL");
595
+ }
596
+ async function execSecondlayer(subcommand, args, deps = {}) {
597
+ if (!ALLOWED.includes(subcommand)) {
598
+ throw new ExecCliError(`subcommand not allowed: ${subcommand}`);
599
+ }
600
+ assertSafeArgs(subcommand, args);
601
+ const argv = [subcommand, ...args];
602
+ if (subcommand === "setup") {
603
+ if (!argv.includes("--yes"))
604
+ argv.push("--yes");
605
+ } else if (!argv.includes("--json")) {
606
+ argv.push("--json");
607
+ }
608
+ const env = deps.env ?? process.env;
609
+ const bin = env.SECONDLAYER_BIN || "secondlayer";
610
+ const cwd = deps.cwd ?? env.SECONDLAYER_CWD ?? process.cwd();
611
+ const spawnFn = deps.spawn ?? spawn;
612
+ const timeout = deps.timeoutMs ?? TIMEOUT_MS[subcommand];
613
+ return new Promise((resolve) => {
614
+ let stdout = "";
615
+ let stderr = "";
616
+ let settled = false;
617
+ const child = spawnFn(bin, argv, {
618
+ cwd,
619
+ env,
620
+ stdio: ["ignore", "pipe", "pipe"],
621
+ detached: process.platform !== "win32",
622
+ shell: false
623
+ });
624
+ const timer = setTimeout(() => {
625
+ killProcessGroup(child);
626
+ finish({
627
+ code: 124,
628
+ stdout,
629
+ stderr: `${stderr}
630
+ timeout after ${timeout}ms`.trim()
631
+ });
632
+ }, timeout);
633
+ function finish(result) {
634
+ if (settled)
635
+ return;
636
+ settled = true;
637
+ clearTimeout(timer);
638
+ resolve(result);
639
+ }
640
+ child.stdout?.on("data", (chunk) => {
641
+ stdout += String(chunk);
642
+ });
643
+ child.stderr?.on("data", (chunk) => {
644
+ stderr += String(chunk);
645
+ });
646
+ child.on("error", (err) => {
647
+ finish({ code: 127, stdout, stderr: err.message });
648
+ });
649
+ child.on("close", (code) => {
650
+ finish({ code: code ?? 1, stdout, stderr });
651
+ });
652
+ });
653
+ }
654
+
655
+ // src/tools/setup.ts
656
+ function cliResponse(result) {
657
+ return jsonResponse(result, result.code !== 0);
658
+ }
659
+ function registerSetupTools(server, exec = execSecondlayer) {
660
+ 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.", {
661
+ network: z7.enum(["mainnet", "testnet", "devnet"]).describe("Stacks network"),
662
+ nodeMode: z7.enum(["external", "stacks", "full"]).describe("Node mode: external, stacks, or full"),
663
+ against: z7.string().optional().describe("Archive manifest URL"),
664
+ dir: z7.string().optional().describe("Compose project directory"),
665
+ skipBootstrap: z7.boolean().optional().describe("Sync from genesis instead of restoring an archive")
666
+ }, async ({ network, nodeMode, against, dir, skipBootstrap }) => {
667
+ const args = ["--yes", "--network", network, "--node-mode", nodeMode];
668
+ if (against !== undefined)
669
+ args.push("--against", against);
670
+ if (dir !== undefined)
671
+ args.push("--dir", dir);
672
+ if (skipBootstrap)
673
+ args.push("--skip-bootstrap");
674
+ return cliResponse(await exec("setup", args));
675
+ });
676
+ 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.", {
677
+ against: z7.string().describe("Archive manifest URL"),
678
+ fromBlock: z7.number().int().nonnegative().optional().describe("Restore from this height instead of genesis"),
679
+ toBlock: z7.number().int().nonnegative().optional().describe("Stop at this height instead of the archive tip")
680
+ }, async ({ against, fromBlock, toBlock }) => {
681
+ const args = ["--against", against, "--yes", "--json"];
682
+ if (fromBlock !== undefined)
683
+ args.push("--from-block", String(fromBlock));
684
+ if (toBlock !== undefined)
685
+ args.push("--to-block", String(toBlock));
686
+ return cliResponse(await exec("bootstrap", args));
687
+ });
688
+ 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.", {
689
+ against: z7.string().describe("Archive manifest URL"),
690
+ apply: z7.boolean().optional().describe("Write the repair (default plan-only)"),
691
+ fromBlock: z7.number().int().nonnegative().optional().describe("First height to consider"),
692
+ toBlock: z7.number().int().nonnegative().optional().describe("Last height to consider")
693
+ }, async ({ against, apply, fromBlock, toBlock }) => {
694
+ const args = ["--against", against, "--json"];
695
+ if (apply)
696
+ args.push("--apply", "--yes");
697
+ if (fromBlock !== undefined)
698
+ args.push("--from-block", String(fromBlock));
699
+ if (toBlock !== undefined)
700
+ args.push("--to-block", String(toBlock));
701
+ return cliResponse(await exec("repair", args));
702
+ });
703
+ }
704
+
430
705
  // src/tools/streams.ts
431
706
  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())]);
707
+ import { z as z8 } from "zod";
708
+ var filterValue = z8.union([z8.string(), z8.array(z8.string())]);
434
709
  function registerStreamsTools(server, clientProvider = getClient) {
435
710
  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
711
  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)"),
712
+ 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"),
713
+ fromHeight: z8.number().int().nonnegative().optional().describe("Start block height (inclusive)"),
714
+ toHeight: z8.number().int().nonnegative().optional().describe("End block height (inclusive)"),
715
+ types: z8.array(z8.enum(STREAMS_EVENT_TYPES)).optional().describe("Event types to include"),
716
+ notTypes: z8.array(z8.enum(STREAMS_EVENT_TYPES)).optional().describe("Event types to exclude (applied after types)"),
442
717
  contractId: filterValue.optional().describe("Contract id, or a list of contract ids to OR together"),
443
718
  sender: filterValue.optional().describe("Sender principal, or a list to OR together"),
444
719
  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)")
720
+ assetIdentifier: z8.string().optional().describe("Asset identifier (contract::asset), e.g. SP…sbtc-token::sbtc-token"),
721
+ limit: z8.number().int().min(1).max(1000).optional().describe("Page size, 1–1000 (default 100)")
447
722
  }, async (params) => jsonResponse(await clientProvider().streams.events.list(params)));
448
723
  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)")
724
+ txId: z8.string().describe("Transaction id (0x-prefixed)")
450
725
  }, async ({ txId }) => jsonResponse(await clientProvider().streams.events.byTxId(txId)));
451
726
  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)")
727
+ heightOrHash: z8.union([z8.number().int().nonnegative(), z8.string()]).describe("Block height (number) or block hash (0x-prefixed string)")
453
728
  }, async ({ heightOrHash }) => jsonResponse(await clientProvider().streams.blocks.events(heightOrHash)));
454
729
  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")
730
+ height: z8.number().int().nonnegative().describe("Block height")
456
731
  }, async ({ height }) => jsonResponse(await clientProvider().streams.canonical(height)));
457
732
  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")
733
+ since: z8.string().describe("Required. ISO 8601 timestamp, or a `next_since` resume token from a prior response"),
734
+ limit: z8.number().int().positive().optional().describe("Max reorgs to return")
460
735
  }, async ({ since, limit }) => jsonResponse(await clientProvider().streams.reorgs.list({
461
736
  since,
462
737
  ...limit !== undefined ? { limit } : {}
@@ -466,19 +741,19 @@ function registerStreamsTools(server, clientProvider = getClient) {
466
741
 
467
742
  // src/tools/subgraphs.ts
468
743
  import { bundleSubgraphCode } from "@secondlayer/bundler";
469
- import { z as z7 } from "zod";
744
+ import { z as z9 } from "zod";
470
745
  function registerSubgraphTools(server, clientProvider = getClient) {
471
746
  defineTool(server, "subgraphs_list", "List all deployed subgraphs. Returns summary fields only; read rows with subgraphs_query.", {}, async () => {
472
747
  const { data } = await clientProvider().subgraphs.list();
473
748
  return jsonResponse(data.map(formatSubgraphSummary));
474
749
  });
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 }) => {
750
+ 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
751
  const detail = await clientProvider().subgraphs.status(name);
477
752
  return jsonResponse(detail);
478
753
  });
479
754
  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")
755
+ name: z9.string().describe("Subgraph name"),
756
+ format: z9.enum(["agent", "openapi", "markdown"]).optional().describe("agent = JSON schema for tool use (default), openapi = OpenAPI JSON, markdown = docs.md")
482
757
  }, async ({ name, format }) => {
483
758
  const client = clientProvider();
484
759
  if (format === "openapi")
@@ -488,15 +763,15 @@ function registerSubgraphTools(server, clientProvider = getClient) {
488
763
  return jsonResponse(await client.subgraphs.schema(name));
489
764
  });
490
765
  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")
766
+ name: z9.string().describe("Subgraph name"),
767
+ table: z9.string().describe("Table name"),
768
+ filters: z9.record(z9.string(), z9.string()).optional().describe('Column filters — plain values or with operators (e.g. {"amount.gte": "1000", "sender": "SP..."})'),
769
+ sort: z9.string().optional().describe("Column to sort by"),
770
+ order: z9.enum(["asc", "desc"]).optional().describe("Sort order"),
771
+ limit: z9.number().max(200).optional().describe("Max rows (default 50, max 200)"),
772
+ offset: z9.number().optional().describe("Offset for pagination"),
773
+ fields: z9.string().optional().describe('Comma-separated column list to return (e.g. "sender,amount")'),
774
+ count: z9.boolean().optional().describe("If true, return row count instead of rows")
500
775
  }, async ({
501
776
  name,
502
777
  table,
@@ -524,15 +799,15 @@ function registerSubgraphTools(server, clientProvider = getClient) {
524
799
  return jsonResponse(result);
525
800
  });
526
801
  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")
802
+ name: z9.string().describe("Subgraph name")
528
803
  }, async ({ name }) => {
529
804
  const result = await clientProvider().subgraphs.reindex(name);
530
805
  return jsonResponse(result);
531
806
  });
532
807
  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)")
808
+ name: z9.string().describe("Subgraph name"),
809
+ fromBlock: z9.number().int().nonnegative().describe("Start block (inclusive)"),
810
+ toBlock: z9.number().int().nonnegative().describe("End block (inclusive)")
536
811
  }, async ({ name, fromBlock, toBlock }) => {
537
812
  const result = await clientProvider().subgraphs.backfill(name, {
538
813
  fromBlock,
@@ -540,15 +815,15 @@ function registerSubgraphTools(server, clientProvider = getClient) {
540
815
  });
541
816
  return jsonResponse(result);
542
817
  });
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 }) => {
818
+ 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
819
  const result = await clientProvider().subgraphs.stop(name);
545
820
  return jsonResponse(result);
546
821
  });
547
822
  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)")
823
+ name: z9.string().describe("Subgraph name"),
824
+ limit: z9.number().int().positive().optional().describe("Max gaps to return"),
825
+ offset: z9.number().int().nonnegative().optional().describe("Pagination offset"),
826
+ resolved: z9.boolean().optional().describe("Filter by resolved state (omit for unresolved only)")
552
827
  }, async ({ name, limit, offset, resolved }) => {
553
828
  const result = await clientProvider().subgraphs.gaps(name, {
554
829
  limit,
@@ -558,20 +833,20 @@ function registerSubgraphTools(server, clientProvider = getClient) {
558
833
  return jsonResponse(result);
559
834
  });
560
835
  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")
836
+ name: z9.string().describe("Subgraph name"),
837
+ operationId: z9.string().optional().describe("Fetch one operation by id (the operationId returned by reindex/backfill/stop); omit for recent history")
563
838
  }, async ({ name, operationId }) => {
564
839
  const client = clientProvider();
565
840
  return jsonResponse(operationId ? await client.subgraphs.getOperation(name, operationId) : await client.subgraphs.operations(name));
566
841
  });
567
- defineTool(server, "subgraphs_delete", "Delete a subgraph permanently.", { name: z7.string().describe("Subgraph name") }, async ({ name }) => {
842
+ defineTool(server, "subgraphs_delete", "Delete a subgraph permanently.", { name: z9.string().describe("Subgraph name") }, async ({ name }) => {
568
843
  const result = await clientProvider().subgraphs.delete(name);
569
844
  return textResponse(result.message);
570
845
  });
571
846
  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")
847
+ code: z9.string().describe("TypeScript source code containing a defineSubgraph() call"),
848
+ startBlock: z9.number().int().nonnegative().optional().describe("Override the definition startBlock for this deploy"),
849
+ dryRun: z9.boolean().optional().describe("Validate and preview the deploy (schema/DDL) without writing changes")
575
850
  }, async ({ code, startBlock, dryRun }) => {
576
851
  const bundled = await bundleSubgraphCode(code);
577
852
  const result = await clientProvider().subgraphs.deploy({
@@ -591,38 +866,38 @@ function registerSubgraphTools(server, clientProvider = getClient) {
591
866
 
592
867
  // src/tools/subscriptions.ts
593
868
  import { CHAIN_TRIGGER_TYPES } from "@secondlayer/shared";
594
- import { z as z8 } from "zod";
869
+ import { z as z10 } from "zod";
595
870
  function registerSubscriptionTools(server, clientProvider = getClient) {
596
871
  defineTool(server, "subscriptions_list", "List all subscriptions for the current account. Returns summary fields (no secrets).", {}, async () => {
597
872
  const { data } = await clientProvider().subscriptions.list();
598
873
  return jsonResponse(data);
599
874
  });
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 }) => {
875
+ 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
876
  const detail = await clientProvider().subscriptions.get(id);
602
877
  return jsonResponse(detail);
603
878
  });
604
879
  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()
880
+ name: z10.string().describe("Human-readable name, unique per account"),
881
+ subgraphName: z10.string().optional().describe("Subgraph to subscribe to (subgraph subscription)"),
882
+ tableName: z10.string().optional().describe("Table within the subgraph (subgraph subscription)"),
883
+ triggers: z10.array(z10.object({
884
+ type: z10.enum(CHAIN_TRIGGER_TYPES),
885
+ contractId: z10.string().optional(),
886
+ functionName: z10.string().optional(),
887
+ caller: z10.string().optional(),
888
+ sender: z10.string().optional(),
889
+ recipient: z10.string().optional(),
890
+ assetIdentifier: z10.string().optional(),
891
+ deployer: z10.string().optional(),
892
+ contractName: z10.string().optional(),
893
+ topic: z10.string().optional(),
894
+ lockedAddress: z10.string().optional(),
895
+ trait: z10.string().optional(),
896
+ minAmount: z10.union([z10.string(), z10.number()]).optional(),
897
+ maxAmount: z10.union([z10.string(), z10.number()]).optional()
623
898
  })).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([
899
+ url: z10.string().describe("Webhook URL"),
900
+ format: z10.enum([
626
901
  "standard-webhooks",
627
902
  "inngest",
628
903
  "trigger",
@@ -630,20 +905,20 @@ function registerSubscriptionTools(server, clientProvider = getClient) {
630
905
  "cloudevents",
631
906
  "raw"
632
907
  ]).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": "..."}')
908
+ runtime: z10.enum(["inngest", "trigger", "cloudflare", "node"]).optional().describe("Receiver runtime label (display only)"),
909
+ filter: z10.record(z10.string(), z10.unknown()).optional().describe('Scalar filter DSL, e.g. {"amount": {"gte": 100}, "sender": "SP..."}'),
910
+ authConfig: z10.record(z10.string(), z10.unknown()).optional().describe('Receiver auth sent with each delivery, e.g. {"type": "bearer", "token": "..."}')
636
911
  }, async (input) => {
637
912
  const res = await clientProvider().subscriptions.create(input);
638
913
  return jsonResponse(res);
639
914
  });
640
915
  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([
916
+ id: z10.string(),
917
+ name: z10.string().optional().describe("Rename the subscription"),
918
+ url: z10.string().optional(),
919
+ filter: z10.record(z10.string(), z10.unknown()).optional(),
920
+ authConfig: z10.record(z10.string(), z10.unknown()).optional().describe("Receiver auth sent with each delivery (bearer/etc.)"),
921
+ format: z10.enum([
647
922
  "standard-webhooks",
648
923
  "inngest",
649
924
  "trigger",
@@ -651,36 +926,36 @@ function registerSubscriptionTools(server, clientProvider = getClient) {
651
926
  "cloudevents",
652
927
  "raw"
653
928
  ]).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()
929
+ runtime: z10.enum(["inngest", "trigger", "cloudflare", "node"]).nullable().optional(),
930
+ maxRetries: z10.number().int().min(0).optional(),
931
+ timeoutMs: z10.number().int().min(100).optional(),
932
+ concurrency: z10.number().int().min(1).optional()
658
933
  }, async ({ id, ...patch }) => {
659
934
  const res = await clientProvider().subscriptions.update(id, patch);
660
935
  return jsonResponse(res);
661
936
  });
662
- defineTool(server, "subscriptions_delete", "Delete a subscription. Pending outbox rows are cascade-deleted.", { id: z8.string() }, async ({ id }) => {
937
+ defineTool(server, "subscriptions_delete", "Delete a subscription. Pending outbox rows are cascade-deleted.", { id: z10.string() }, async ({ id }) => {
663
938
  const res = await clientProvider().subscriptions.delete(id);
664
939
  return jsonResponse(res);
665
940
  });
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 }) => {
941
+ 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
942
  const res = await clientProvider().subscriptions.test(id);
668
943
  return jsonResponse(res);
669
944
  });
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)));
945
+ 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)));
946
+ 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)));
947
+ 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)));
948
+ 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)));
949
+ 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
950
  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)")
951
+ id: z10.string().describe("Subscription id"),
952
+ outboxId: z10.string().describe("Outbox id of the dead delivery (from subscriptions_dead)")
678
953
  }, async ({ id, outboxId }) => jsonResponse(await clientProvider().subscriptions.requeue(id, outboxId)));
679
954
  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")
955
+ id: z10.string(),
956
+ fromBlock: z10.number().int().nonnegative(),
957
+ toBlock: z10.number().int().nonnegative(),
958
+ force: z10.string().optional().describe("Idempotency suffix to force a duplicate replay of the range")
684
959
  }, async ({ id, fromBlock, toBlock, force }) => {
685
960
  const res = await clientProvider().subscriptions.replay(id, {
686
961
  fromBlock,
@@ -706,6 +981,9 @@ function createServer() {
706
981
  registerStreamsTools(server);
707
982
  registerContractTools(server);
708
983
  registerCodegenTools(server);
984
+ registerInstanceTools(server);
985
+ registerArchiveTools(server);
986
+ registerSetupTools(server);
709
987
  const baseUrl = process.env.SECONDLAYER_API_URL || process.env.SL_API_URL || "http://127.0.0.1:3800";
710
988
  if (isHostedArchiveUrl(baseUrl)) {
711
989
  registerAccountTools(server);
@@ -719,5 +997,5 @@ var server = createServer();
719
997
  var transport = new StdioServerTransport;
720
998
  await server.connect(transport);
721
999
 
722
- //# debugId=A32A9DB8FD9D2A0F64756E2164756E21
1000
+ //# debugId=6E82BB2F3FB90EC564756E2164756E21
723
1001
  //# sourceMappingURL=bin.js.map