@secondlayer/mcp 10.0.1 → 11.0.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
@@ -223,7 +223,6 @@ var PRODUCT_BLURBS = {
223
223
  codegen: "ORM schemas for the tables you read",
224
224
  instance: "decoder health and empty-index diagnosis",
225
225
  archive: "signed archive verify, bootstrap/repair, quote, latest pointer",
226
- setup: "one-command self-host onboarding",
227
226
  credits: "archive credits balance at api.secondlayer.tools"
228
227
  };
229
228
  var PRODUCT_ORDER = [
@@ -236,7 +235,6 @@ var PRODUCT_ORDER = [
236
235
  "codegen",
237
236
  "instance",
238
237
  "archive",
239
- "setup",
240
238
  "credits"
241
239
  ];
242
240
  function buildCapabilities() {
@@ -441,229 +439,22 @@ function registerAccountTools(server) {
441
439
  }, async ({ name }) => jsonResponse(await apiRequest("POST", "/api/keys", { name })));
442
440
  }
443
441
 
444
- // src/tools/archive.ts
442
+ // src/tools/archive-cli.ts
445
443
  import { z as z2 } from "zod";
446
- var FLOW = ["bootstrap", "repair"];
447
- function registerArchiveTools(server, clientProvider = getClient, archiveOpsClientProvider = getArchiveOpsClient) {
448
- 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.", {
449
- against: z2.string().describe("Archive manifest URL"),
450
- fromBlock: z2.number().int().nonnegative().optional().describe("First height (inclusive)"),
451
- toBlock: z2.number().int().nonnegative().optional().describe("Last height (inclusive)"),
452
- target: z2.string().optional().describe("Verify target (default raw)")
453
- }, async ({ against, fromBlock, toBlock, target }) => jsonResponse(await clientProvider().archive.verify({
454
- against,
455
- fromBlock,
456
- toBlock,
457
- target
458
- })));
459
- 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.", {
460
- against: z2.string().optional().describe("Override latest.json URL (default official tree)")
461
- }, async ({ against }) => jsonResponse(await archiveOpsClientProvider().archive.latest(against)));
462
- 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.", {
463
- paths: z2.array(z2.string()).describe("Partition paths to price"),
464
- flow: z2.enum(FLOW).describe("bootstrap or repair")
465
- }, async ({ paths, flow }) => jsonResponse(await archiveOpsClientProvider().archive.quote({ paths, flow })));
466
- 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()));
467
- }
468
-
469
- // src/tools/codegen.ts
470
- import {
471
- generateIndexSchema
472
- } from "@secondlayer/subgraphs";
473
- import { z as z3 } from "zod";
474
- var TARGETS = ["prisma", "kysely", "drizzle", "json-schema"];
475
- function registerCodegenTools(server) {
476
- 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.", {
477
- target: z3.enum(TARGETS).optional().describe("Output flavor (default kysely)"),
478
- tables: z3.array(z3.string()).optional().describe("Restrict to these Index tables (default: all)"),
479
- schemaName: z3.string().optional().describe("Postgres schema to qualify table names with"),
480
- datasourceEnv: z3.string().optional().describe("Prisma only: datasource url env var (default DATABASE_URL)")
481
- }, ({ target, tables, schemaName, datasourceEnv }) => textResponse(generateIndexSchema(target ?? "kysely", {
482
- tables,
483
- schemaName,
484
- datasourceEnv
485
- })));
486
- }
487
-
488
- // src/tools/contracts.ts
489
- import { z as z4 } from "zod";
490
- function registerContractTools(server, clientProvider = getClient) {
491
- 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.', {
492
- trait: z4.string().describe('Required. Trait to match (e.g. "sip-010").'),
493
- conformance: z4.enum(["declared", "inferred", "any"]).optional().describe("declared = parsed from source, inferred = ABI shape-match, any = either (default)"),
494
- include: z4.literal("abi").optional().describe(`Set to "abi" to include each contract's full ABI`),
495
- limit: z4.number().optional().describe("Page size, 1–500 (default 100)"),
496
- cursor: z4.string().optional().describe("Opaque cursor from a prior response's next_cursor")
497
- }, async (params) => jsonResponse(await clientProvider().contracts.list(params)));
498
- 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.", {
499
- contractId: z4.string().describe("Fully qualified contract id (e.g. SP….amm-pool-v2-01)")
500
- }, async ({ contractId }) => {
501
- const contract = await clientProvider().contracts.get(contractId, {
502
- includeAbi: true
503
- });
504
- return contract ? jsonResponse(contract) : jsonResponse({
505
- error: {
506
- type: "not_found",
507
- status: 404,
508
- message: `Contract not in registry: ${contractId}`
509
- }
510
- }, true);
511
- });
512
- }
513
-
514
- // src/tools/index.ts
515
- import { DECODED_EVENT_TYPES } from "@secondlayer/shared";
516
- import { z as z5 } from "zod";
517
- var INDEX_EVENT_TYPES = DECODED_EVENT_TYPES;
518
- var rangeFilters = {
519
- contractId: z5.string().optional().describe("Filter by contract id"),
520
- fromHeight: z5.number().optional().describe("Start block height (inclusive)"),
521
- toHeight: z5.number().optional().describe("End block height (inclusive)"),
522
- cursor: z5.string().optional().describe("Opaque cursor from a prior response's next_cursor"),
523
- limit: z5.number().optional().describe("Max rows for this page")
524
- };
525
- var heightFilters = {
526
- fromHeight: rangeFilters.fromHeight,
527
- toHeight: rangeFilters.toHeight,
528
- cursor: rangeFilters.cursor,
529
- limit: rangeFilters.limit
530
- };
531
- function registerIndexTools(server, clientProvider = getClient) {
532
- defineTool(server, "index_ft_transfers", "List decoded SIP-010 fungible-token transfers from Index. Reads are keyless.", {
533
- ...rangeFilters,
534
- sender: z5.string().optional().describe("Filter by sender principal"),
535
- recipient: z5.string().optional().describe("Filter by recipient principal"),
536
- assetIdentifier: z5.string().optional().describe("Filter by asset identifier (contract::asset), e.g. SP…sbtc-token::sbtc-token")
537
- }, async (params) => jsonResponse(await clientProvider().index.ftTransfers.list(params)));
538
- defineTool(server, "index_nft_transfers", "List decoded SIP-009 non-fungible-token transfers from Index. Reads are keyless.", {
539
- ...rangeFilters,
540
- sender: z5.string().optional().describe("Filter by sender principal"),
541
- recipient: z5.string().optional().describe("Filter by recipient principal"),
542
- assetIdentifier: z5.string().optional().describe("Filter by asset identifier (contract::asset)")
543
- }, async (params) => jsonResponse(await clientProvider().index.nftTransfers.list(params)));
544
- 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.", {
545
- eventType: z5.enum(INDEX_EVENT_TYPES).describe("Required. Decoded event type to list."),
546
- ...rangeFilters,
547
- sender: z5.string().optional().describe("Filter by sender principal"),
548
- recipient: z5.string().optional().describe("Filter by recipient principal"),
549
- assetIdentifier: z5.string().optional().describe("Filter by asset identifier where applicable"),
550
- 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."),
551
- 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.")
552
- }, async (params) => jsonResponse(await clientProvider().index.events.list(params)));
553
- 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.", {
554
- ...rangeFilters,
555
- functionName: z5.string().optional().describe("Filter by called function name"),
556
- sender: z5.string().optional().describe("Filter by caller principal"),
557
- trait: z5.string().optional().describe("Match contracts conforming to a trait/standard (e.g. sip-010). Mutually exclusive with contractId.")
558
- }, async (params) => jsonResponse(await clientProvider().index.contractCalls.list(params)));
559
- defineTool(server, "index_blocks", "List decoded blocks from Index. Reads are keyless.", { ...heightFilters }, async (params) => jsonResponse(await clientProvider().index.blocks.list(params)));
560
- defineTool(server, "index_transactions", "List decoded transactions from Index. Filter by type, sender, or contract. Reads are keyless.", {
561
- ...rangeFilters,
562
- type: z5.string().optional().describe("Filter by transaction type"),
563
- sender: z5.string().optional().describe("Filter by sender principal")
564
- }, async (params) => jsonResponse(await clientProvider().index.transactions.list(params)));
565
- 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.", {
566
- contractId: z5.string().describe("Contract id (SP….name) whose print events to profile")
567
- }, async (params) => jsonResponse(await clientProvider().index.printSchema(params.contractId)));
568
- 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()));
569
- 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.", {
570
- requests: z5.array(z5.object({
571
- path: z5.string().describe("Public /v1 read path"),
572
- params: z5.record(z5.string(), z5.string()).optional()
573
- })).min(1).max(10).describe("Read descriptors, executed concurrently")
574
- }, async (params) => jsonResponse(await clientProvider().batch(params.requests)));
575
- }
576
-
577
- // src/tools/instance.ts
578
- function registerInstanceTools(server, clientProvider = getClient) {
579
- 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 () => {
580
- const client = clientProvider();
581
- const status = await client.instance.status();
582
- const diagnosis = await client.instance.diagnose();
583
- return jsonResponse({ status, diagnosis });
584
- });
585
- }
586
-
587
- // src/tools/scaffold.ts
588
- import {
589
- generatePrintSchemaSubgraph,
590
- generateSubgraphCode,
591
- generateTokenSubgraphFromAbi
592
- } from "@secondlayer/scaffold";
593
- import { z as z6 } from "zod";
594
- async function fetchAbi(clientProvider, contractId) {
595
- const contract = await clientProvider().contracts.get(contractId, {
596
- includeAbi: true
597
- });
598
- if (!contract)
599
- throw new Error(`Contract not found: ${contractId}`);
600
- const abi = contract.abi;
601
- if (!abi) {
602
- throw new Error(`No ABI available for ${contractId} (abi_status: ${contract.abi_status})`);
603
- }
604
- return { functions: abi.functions ?? [], abi };
605
- }
606
- function registerScaffoldTools(server, clientProvider = getClient) {
607
- defineTool(server, "subgraphs_scaffold", "Generate a subgraph from observed print events when available; ABI token transfers or public functions only when the contract has never printed. Review the TypeScript, run subgraphs_test until ok: true with written >= 1, read skipped, then subgraphs_deploy. dryRun is DDL only.", {
608
- contractId: z6.string().describe("Fully qualified contract ID (e.g. SP102V8P0F7JX67ARQ77WEA3D3CFB5XW39REDT0AM.amm-pool-v2-01)"),
609
- subgraphName: z6.string().optional().describe("Override the subgraph name (defaults to contract name)")
610
- }, async ({ contractId, subgraphName }) => {
611
- const printSchema = await clientProvider().index.printSchema(contractId);
612
- if (printSchema && printSchema.topics.length > 0) {
613
- const code = generatePrintSchemaSubgraph({
614
- contractId,
615
- name: subgraphName,
616
- topics: printSchema.topics,
617
- sample: printSchema.sample
618
- });
619
- return { content: [{ type: "text", text: code }] };
620
- }
621
- const { functions, abi } = await fetchAbi(clientProvider, contractId);
622
- const token = generateTokenSubgraphFromAbi({
623
- contractId,
624
- abi,
625
- name: subgraphName
626
- });
627
- if (token) {
628
- return { content: [{ type: "text", text: token }] };
629
- }
630
- const code = generateSubgraphCode(contractId, functions, subgraphName);
631
- return { content: [{ type: "text", text: code }] };
632
- });
633
- }
634
-
635
- // src/tools/setup.ts
636
- import { z as z7 } from "zod";
637
444
 
638
445
  // src/lib/exec-cli.ts
639
446
  import {
640
447
  spawn
641
448
  } from "node:child_process";
642
- var ALLOWED = ["setup", "bootstrap", "repair", "verify"];
449
+ var ALLOWED = ["bootstrap", "repair", "verify"];
643
450
  var TIMEOUT_MS = {
644
- setup: 15 * 60 * 1000,
645
451
  bootstrap: 10 * 60 * 1000,
646
452
  repair: 10 * 60 * 1000,
647
453
  verify: 2 * 60 * 1000
648
454
  };
649
- var VALUE_FLAGS = new Set([
650
- "--against",
651
- "--from-block",
652
- "--to-block",
653
- "--network",
654
- "--node-mode",
655
- "--dir"
656
- ]);
657
- var BOOL_FLAGS = new Set(["--yes", "--json", "--apply", "--skip-bootstrap"]);
455
+ var VALUE_FLAGS = new Set(["--against", "--from-block", "--to-block"]);
456
+ var BOOL_FLAGS = new Set(["--yes", "--json", "--apply"]);
658
457
  var FLAGS_BY_CMD = {
659
- setup: new Set([
660
- "--yes",
661
- "--network",
662
- "--node-mode",
663
- "--against",
664
- "--dir",
665
- "--skip-bootstrap"
666
- ]),
667
458
  bootstrap: new Set([
668
459
  "--against",
669
460
  "--yes",
@@ -738,12 +529,8 @@ async function execSecondlayer(subcommand, args, deps = {}) {
738
529
  }
739
530
  assertSafeArgs(subcommand, args);
740
531
  const argv = [subcommand, ...args];
741
- if (subcommand === "setup") {
742
- if (!argv.includes("--yes"))
743
- argv.push("--yes");
744
- } else if (!argv.includes("--json")) {
532
+ if (!argv.includes("--json"))
745
533
  argv.push("--json");
746
- }
747
534
  const env = deps.env ?? process.env;
748
535
  const bin = env.SECONDLAYER_BIN || "secondlayer";
749
536
  const cwd = deps.cwd ?? env.SECONDLAYER_CWD ?? process.cwd();
@@ -791,31 +578,15 @@ timeout after ${timeout}ms`.trim()
791
578
  });
792
579
  }
793
580
 
794
- // src/tools/setup.ts
581
+ // src/tools/archive-cli.ts
795
582
  function cliResponse(result) {
796
583
  return jsonResponse(result, result.code !== 0);
797
584
  }
798
- function registerSetupTools(server, exec = execSecondlayer) {
799
- 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.", {
800
- network: z7.enum(["mainnet", "testnet", "devnet"]).describe("Stacks network"),
801
- nodeMode: z7.enum(["external", "stacks", "full"]).describe("Node mode: external, stacks, or full"),
802
- against: z7.string().optional().describe("Archive manifest URL"),
803
- dir: z7.string().optional().describe("Compose project directory"),
804
- skipBootstrap: z7.boolean().optional().describe("Sync from genesis instead of restoring an archive")
805
- }, async ({ network, nodeMode, against, dir, skipBootstrap }) => {
806
- const args = ["--yes", "--network", network, "--node-mode", nodeMode];
807
- if (against !== undefined)
808
- args.push("--against", against);
809
- if (dir !== undefined)
810
- args.push("--dir", dir);
811
- if (skipBootstrap)
812
- args.push("--skip-bootstrap");
813
- return cliResponse(await exec("setup", args));
814
- });
585
+ function registerArchiveCliTools(server, exec = execSecondlayer) {
815
586
  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.", {
816
- against: z7.string().describe("Archive manifest URL"),
817
- fromBlock: z7.number().int().nonnegative().optional().describe("Restore from this height instead of genesis"),
818
- toBlock: z7.number().int().nonnegative().optional().describe("Stop at this height instead of the archive tip")
587
+ against: z2.string().describe("Archive manifest URL"),
588
+ fromBlock: z2.number().int().nonnegative().optional().describe("Restore from this height instead of genesis"),
589
+ toBlock: z2.number().int().nonnegative().optional().describe("Stop at this height instead of the archive tip")
819
590
  }, async ({ against, fromBlock, toBlock }) => {
820
591
  const args = ["--against", against, "--yes", "--json"];
821
592
  if (fromBlock !== undefined)
@@ -825,10 +596,10 @@ function registerSetupTools(server, exec = execSecondlayer) {
825
596
  return cliResponse(await exec("bootstrap", args));
826
597
  });
827
598
  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.", {
828
- against: z7.string().describe("Archive manifest URL"),
829
- apply: z7.boolean().optional().describe("Write the repair (default plan-only)"),
830
- fromBlock: z7.number().int().nonnegative().optional().describe("First height to consider"),
831
- toBlock: z7.number().int().nonnegative().optional().describe("Last height to consider")
599
+ against: z2.string().describe("Archive manifest URL"),
600
+ apply: z2.boolean().optional().describe("Write the repair (default plan-only)"),
601
+ fromBlock: z2.number().int().nonnegative().optional().describe("First height to consider"),
602
+ toBlock: z2.number().int().nonnegative().optional().describe("Last height to consider")
832
603
  }, async ({ against, apply, fromBlock, toBlock }) => {
833
604
  const args = ["--against", against, "--json"];
834
605
  if (apply)
@@ -841,6 +612,197 @@ function registerSetupTools(server, exec = execSecondlayer) {
841
612
  });
842
613
  }
843
614
 
615
+ // src/tools/archive.ts
616
+ import { z as z3 } from "zod";
617
+ var FLOW = ["bootstrap", "repair"];
618
+ function registerArchiveTools(server, clientProvider = getClient, archiveOpsClientProvider = getArchiveOpsClient) {
619
+ 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.", {
620
+ against: z3.string().describe("Archive manifest URL"),
621
+ fromBlock: z3.number().int().nonnegative().optional().describe("First height (inclusive)"),
622
+ toBlock: z3.number().int().nonnegative().optional().describe("Last height (inclusive)"),
623
+ target: z3.string().optional().describe("Verify target (default raw)")
624
+ }, async ({ against, fromBlock, toBlock, target }) => jsonResponse(await clientProvider().archive.verify({
625
+ against,
626
+ fromBlock,
627
+ toBlock,
628
+ target
629
+ })));
630
+ 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.", {
631
+ against: z3.string().optional().describe("Override latest.json URL (default official tree)")
632
+ }, async ({ against }) => jsonResponse(await archiveOpsClientProvider().archive.latest(against)));
633
+ 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.", {
634
+ paths: z3.array(z3.string()).describe("Partition paths to price"),
635
+ flow: z3.enum(FLOW).describe("bootstrap or repair")
636
+ }, async ({ paths, flow }) => jsonResponse(await archiveOpsClientProvider().archive.quote({ paths, flow })));
637
+ 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()));
638
+ }
639
+
640
+ // src/tools/codegen.ts
641
+ import {
642
+ generateIndexSchema
643
+ } from "@secondlayer/subgraphs";
644
+ import { z as z4 } from "zod";
645
+ var TARGETS = ["prisma", "kysely", "drizzle", "json-schema"];
646
+ function registerCodegenTools(server) {
647
+ 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.", {
648
+ target: z4.enum(TARGETS).optional().describe("Output flavor (default kysely)"),
649
+ tables: z4.array(z4.string()).optional().describe("Restrict to these Index tables (default: all)"),
650
+ schemaName: z4.string().optional().describe("Postgres schema to qualify table names with"),
651
+ datasourceEnv: z4.string().optional().describe("Prisma only: datasource url env var (default DATABASE_URL)")
652
+ }, ({ target, tables, schemaName, datasourceEnv }) => textResponse(generateIndexSchema(target ?? "kysely", {
653
+ tables,
654
+ schemaName,
655
+ datasourceEnv
656
+ })));
657
+ }
658
+
659
+ // src/tools/contracts.ts
660
+ import { z as z5 } from "zod";
661
+ function registerContractTools(server, clientProvider = getClient) {
662
+ 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.', {
663
+ trait: z5.string().describe('Required. Trait to match (e.g. "sip-010").'),
664
+ conformance: z5.enum(["declared", "inferred", "any"]).optional().describe("declared = parsed from source, inferred = ABI shape-match, any = either (default)"),
665
+ include: z5.literal("abi").optional().describe(`Set to "abi" to include each contract's full ABI`),
666
+ limit: z5.number().optional().describe("Page size, 1–500 (default 100)"),
667
+ cursor: z5.string().optional().describe("Opaque cursor from a prior response's next_cursor")
668
+ }, async (params) => jsonResponse(await clientProvider().contracts.list(params)));
669
+ 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.", {
670
+ contractId: z5.string().describe("Fully qualified contract id (e.g. SP….amm-pool-v2-01)")
671
+ }, async ({ contractId }) => {
672
+ const contract = await clientProvider().contracts.get(contractId, {
673
+ includeAbi: true
674
+ });
675
+ return contract ? jsonResponse(contract) : jsonResponse({
676
+ error: {
677
+ type: "not_found",
678
+ status: 404,
679
+ message: `Contract not in registry: ${contractId}`
680
+ }
681
+ }, true);
682
+ });
683
+ }
684
+
685
+ // src/tools/index.ts
686
+ import { DECODED_EVENT_TYPES } from "@secondlayer/shared";
687
+ import { z as z6 } from "zod";
688
+ var INDEX_EVENT_TYPES = DECODED_EVENT_TYPES;
689
+ var rangeFilters = {
690
+ contractId: z6.string().optional().describe("Filter by contract id"),
691
+ fromHeight: z6.number().optional().describe("Start block height (inclusive)"),
692
+ toHeight: z6.number().optional().describe("End block height (inclusive)"),
693
+ cursor: z6.string().optional().describe("Opaque cursor from a prior response's next_cursor"),
694
+ limit: z6.number().optional().describe("Max rows for this page")
695
+ };
696
+ var heightFilters = {
697
+ fromHeight: rangeFilters.fromHeight,
698
+ toHeight: rangeFilters.toHeight,
699
+ cursor: rangeFilters.cursor,
700
+ limit: rangeFilters.limit
701
+ };
702
+ function registerIndexTools(server, clientProvider = getClient) {
703
+ defineTool(server, "index_ft_transfers", "List decoded SIP-010 fungible-token transfers from Index. Reads are keyless.", {
704
+ ...rangeFilters,
705
+ sender: z6.string().optional().describe("Filter by sender principal"),
706
+ recipient: z6.string().optional().describe("Filter by recipient principal"),
707
+ assetIdentifier: z6.string().optional().describe("Filter by asset identifier (contract::asset), e.g. SP…sbtc-token::sbtc-token")
708
+ }, async (params) => jsonResponse(await clientProvider().index.ftTransfers.list(params)));
709
+ defineTool(server, "index_nft_transfers", "List decoded SIP-009 non-fungible-token transfers from Index. Reads are keyless.", {
710
+ ...rangeFilters,
711
+ sender: z6.string().optional().describe("Filter by sender principal"),
712
+ recipient: z6.string().optional().describe("Filter by recipient principal"),
713
+ assetIdentifier: z6.string().optional().describe("Filter by asset identifier (contract::asset)")
714
+ }, async (params) => jsonResponse(await clientProvider().index.nftTransfers.list(params)));
715
+ 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.", {
716
+ eventType: z6.enum(INDEX_EVENT_TYPES).describe("Required. Decoded event type to list."),
717
+ ...rangeFilters,
718
+ sender: z6.string().optional().describe("Filter by sender principal"),
719
+ recipient: z6.string().optional().describe("Filter by recipient principal"),
720
+ assetIdentifier: z6.string().optional().describe("Filter by asset identifier where applicable"),
721
+ trait: z6.string().optional().describe("Match contracts conforming to a trait/standard (e.g. sip-010). Mutually exclusive with contractId; contract-keyed event types only."),
722
+ txContext: z6.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.")
723
+ }, async (params) => jsonResponse(await clientProvider().index.events.list(params)));
724
+ 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.", {
725
+ ...rangeFilters,
726
+ functionName: z6.string().optional().describe("Filter by called function name"),
727
+ sender: z6.string().optional().describe("Filter by caller principal"),
728
+ trait: z6.string().optional().describe("Match contracts conforming to a trait/standard (e.g. sip-010). Mutually exclusive with contractId.")
729
+ }, async (params) => jsonResponse(await clientProvider().index.contractCalls.list(params)));
730
+ defineTool(server, "index_blocks", "List decoded blocks from Index. Reads are keyless.", { ...heightFilters }, async (params) => jsonResponse(await clientProvider().index.blocks.list(params)));
731
+ defineTool(server, "index_transactions", "List decoded transactions from Index. Filter by type, sender, or contract. Reads are keyless.", {
732
+ ...rangeFilters,
733
+ type: z6.string().optional().describe("Filter by transaction type"),
734
+ sender: z6.string().optional().describe("Filter by sender principal")
735
+ }, async (params) => jsonResponse(await clientProvider().index.transactions.list(params)));
736
+ 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.", {
737
+ contractId: z6.string().describe("Contract id (SP….name) whose print events to profile")
738
+ }, async (params) => jsonResponse(await clientProvider().index.printSchema(params.contractId)));
739
+ 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()));
740
+ 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.", {
741
+ requests: z6.array(z6.object({
742
+ path: z6.string().describe("Public /v1 read path"),
743
+ params: z6.record(z6.string(), z6.string()).optional()
744
+ })).min(1).max(10).describe("Read descriptors, executed concurrently")
745
+ }, async (params) => jsonResponse(await clientProvider().batch(params.requests)));
746
+ }
747
+
748
+ // src/tools/instance.ts
749
+ function registerInstanceTools(server, clientProvider = getClient) {
750
+ defineTool(server, "instance_status", "Decoder health and empty-index diagnosis from GET /public/status. If state is empty-index, next tool is archive_bootstrap. 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 () => {
751
+ const client = clientProvider();
752
+ const status = await client.instance.status();
753
+ const diagnosis = await client.instance.diagnose();
754
+ return jsonResponse({ status, diagnosis });
755
+ });
756
+ }
757
+
758
+ // src/tools/scaffold.ts
759
+ import {
760
+ generatePrintSchemaSubgraph,
761
+ generateSubgraphCode,
762
+ generateTokenSubgraphFromAbi
763
+ } from "@secondlayer/scaffold";
764
+ import { z as z7 } from "zod";
765
+ async function fetchAbi(clientProvider, contractId) {
766
+ const contract = await clientProvider().contracts.get(contractId, {
767
+ includeAbi: true
768
+ });
769
+ if (!contract)
770
+ throw new Error(`Contract not found: ${contractId}`);
771
+ const abi = contract.abi;
772
+ if (!abi) {
773
+ throw new Error(`No ABI available for ${contractId} (abi_status: ${contract.abi_status})`);
774
+ }
775
+ return { functions: abi.functions ?? [], abi };
776
+ }
777
+ function registerScaffoldTools(server, clientProvider = getClient) {
778
+ defineTool(server, "subgraphs_scaffold", "Generate a subgraph from observed print events when available; ABI token transfers or public functions only when the contract has never printed. Review the TypeScript, run subgraphs_test until ok: true with written >= 1, read skipped, then subgraphs_deploy. dryRun is DDL only.", {
779
+ contractId: z7.string().describe("Fully qualified contract ID (e.g. SP102V8P0F7JX67ARQ77WEA3D3CFB5XW39REDT0AM.amm-pool-v2-01)"),
780
+ subgraphName: z7.string().optional().describe("Override the subgraph name (defaults to contract name)")
781
+ }, async ({ contractId, subgraphName }) => {
782
+ const printSchema = await clientProvider().index.printSchema(contractId);
783
+ if (printSchema && printSchema.topics.length > 0) {
784
+ const code = generatePrintSchemaSubgraph({
785
+ contractId,
786
+ name: subgraphName,
787
+ topics: printSchema.topics,
788
+ sample: printSchema.sample
789
+ });
790
+ return { content: [{ type: "text", text: code }] };
791
+ }
792
+ const { functions, abi } = await fetchAbi(clientProvider, contractId);
793
+ const token = generateTokenSubgraphFromAbi({
794
+ contractId,
795
+ abi,
796
+ name: subgraphName
797
+ });
798
+ if (token) {
799
+ return { content: [{ type: "text", text: token }] };
800
+ }
801
+ const code = generateSubgraphCode(contractId, functions, subgraphName);
802
+ return { content: [{ type: "text", text: code }] };
803
+ });
804
+ }
805
+
844
806
  // src/tools/streams.ts
845
807
  function registerStreamsTools(server, clientProvider = getClient) {
846
808
  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()));
@@ -1189,7 +1151,7 @@ var TOOL_GROUPS = [
1189
1151
  { group: "codegen", register: registerCodegenTools },
1190
1152
  { group: "instance", register: registerInstanceTools },
1191
1153
  { group: "archive", register: registerArchiveTools },
1192
- { group: "setup", register: registerSetupTools },
1154
+ { group: "archive", register: registerArchiveCliTools },
1193
1155
  { group: "account", register: registerAccountTools, hostedOnly: true }
1194
1156
  ];
1195
1157
 
@@ -1216,5 +1178,5 @@ var server = createServer();
1216
1178
  var transport = new StdioServerTransport;
1217
1179
  await server.connect(transport);
1218
1180
 
1219
- //# debugId=A9F8E1BED778D12264756E2164756E21
1181
+ //# debugId=7D6D11FBC95E490C64756E2164756E21
1220
1182
  //# sourceMappingURL=bin.js.map