@secondlayer/mcp 3.10.0 → 4.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
@@ -10,7 +10,7 @@ import { fileURLToPath } from "node:url";
10
10
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
11
11
 
12
12
  // src/resources.ts
13
- import { CHAIN_TRIGGER_FIELDS, DECODED_EVENT_TYPES } from "@secondlayer/shared";
13
+ import { CHAIN_TRIGGER_FIELDS } from "@secondlayer/shared";
14
14
  import { TRAIT_STANDARDS } from "@secondlayer/stacks/clarity";
15
15
  import { TYPE_MAP } from "@secondlayer/subgraphs/schema";
16
16
 
@@ -198,14 +198,13 @@ var COLUMN_TYPES = [
198
198
  }
199
199
  ];
200
200
  var PRODUCT_BLURBS = {
201
- index: "decoded L2 events, contract calls, blocks, transactions, stacking, mempool",
202
- streams: "raw canonical chain event firehose",
203
- contracts: "trait-based contract discovery",
201
+ index: "decoded L2 events, transfers, contract calls, blocks, transactions",
202
+ streams: "bulk parquet dumps of the raw chain event firehose",
203
+ contracts: "trait-based contract discovery and ABIs",
204
204
  subgraphs: "author/deploy/query custom indexes",
205
205
  subscriptions: "webhook delivery on subgraph rows or raw chain events",
206
- account: "identity, plan, billing, usage, spend caps, and API keys",
207
- project: "create/manage projects and view their team",
208
- scaffold: "generate typed contract clients from a deployment or ABI"
206
+ account: "identity and self-provisioned API keys",
207
+ scaffold: "generate deploy-ready subgraph code from a deployed contract"
209
208
  };
210
209
  var PRODUCT_ORDER = [
211
210
  "index",
@@ -214,7 +213,6 @@ var PRODUCT_ORDER = [
214
213
  "subgraphs",
215
214
  "subscriptions",
216
215
  "account",
217
- "project",
218
216
  "scaffold"
219
217
  ];
220
218
  function buildCapabilities() {
@@ -321,29 +319,6 @@ function registerResources(server) {
321
319
  }
322
320
  ]
323
321
  }));
324
- server.resource("streams-filters", "secondlayer://streams-filters", {
325
- description: "Streams firehose vocabulary — the decoded event types and the filter fields accepted by streams_events / streams_consume."
326
- }, async () => ({
327
- contents: [
328
- {
329
- uri: "secondlayer://streams-filters",
330
- mimeType: "application/json",
331
- text: JSON.stringify({
332
- eventTypes: [...DECODED_EVENT_TYPES],
333
- filters: {
334
- types: "include only these event types (array)",
335
- notTypes: "exclude these event types (array)",
336
- contractId: "match a contract id",
337
- sender: "match the sender principal",
338
- recipient: "match the recipient principal",
339
- assetIdentifier: "match the asset identifier (contract::asset)",
340
- fromHeight: "start block height (inclusive)",
341
- toHeight: "end block height (inclusive)"
342
- }
343
- }, null, 2)
344
- }
345
- ]
346
- }));
347
322
  server.resource("chain-triggers", "secondlayer://chain-triggers", {
348
323
  description: "Chain-subscription trigger types and the filter fields each accepts (for subscriptions_create triggers)."
349
324
  }, async () => ({
@@ -364,50 +339,13 @@ function registerAccountTools(server) {
364
339
  const result = await apiRequest("GET", "/api/accounts/me");
365
340
  return jsonResponse(result);
366
341
  });
367
- defineTool(server, "account_update", "Update the authenticated account's profile. Requires an API key.", {
368
- displayName: z.string().optional().describe("Display name"),
369
- bio: z.string().optional().describe("Profile bio"),
370
- slug: z.string().optional().describe("Account URL slug")
371
- }, async ({ displayName, bio, slug }) => {
372
- const body = {};
373
- if (displayName !== undefined)
374
- body.display_name = displayName;
375
- if (bio !== undefined)
376
- body.bio = bio;
377
- if (slug !== undefined)
378
- body.slug = slug;
379
- const result = await apiRequest("PATCH", "/api/accounts/me", body);
380
- return jsonResponse(result);
381
- });
382
- defineTool(server, "account_billing", "Show the account's plan and subscription/billing status. Requires an API key. (Plan upgrade / Stripe portal / checkout are deliberately not agent tools — they are session-only human-payment flows; use account_set_caps to bound spend.)", {}, async () => {
383
- const result = await apiRequest("GET", "/api/billing/status");
384
- return jsonResponse(result);
385
- });
386
342
  defineTool(server, "account_create_key", "Mint a scoped streams/index read API key so the agent can self-provision access. Requires an account-level (owner) API key. The returned `key` is shown ONCE — forward it to the user to set as SL_API_KEY.", {
387
343
  product: z.enum(["streams", "index"]).optional().describe("Key scope (default streams)"),
388
344
  name: z.string().optional().describe("Optional label for the key")
389
345
  }, async ({ product, name }) => jsonResponse(await getClient().apiKeys.create({ product, name })));
390
- defineTool(server, "account_list_keys", "List the account's API keys (metadata only — prefix, name, status, product, tier, last used; never the plaintext). Requires an account-level (owner) API key.", {}, async () => jsonResponse(await getClient().apiKeys.list()));
391
- defineTool(server, "account_revoke_key", "Revoke an API key by id. Requests using that key stop working immediately. Requires an account-level (owner) API key.", { id: z.string().describe("Key id from account_list_keys") }, async ({ id }) => jsonResponse(await getClient().apiKeys.revoke(id)));
392
- defineTool(server, "account_usage", "Show the current billing period's usage snapshot: spend (with cap/projection), compute, storage, and per-project breakdown. Requires an API key.", {}, async () => jsonResponse(await apiRequest("GET", "/api/accounts/usage")));
393
- defineTool(server, "account_get_caps", "Show the account's spend caps and alert threshold. Requires an account-level (owner) API key.", {}, async () => jsonResponse(await apiRequest("GET", "/api/billing/caps")));
394
- defineTool(server, "account_set_caps", "Set the account's spend caps and alert threshold (no payment — just bounds spend). Requires an account-level (owner) API key.", {
395
- monthlyCapCents: z.number().int().nonnegative().optional().describe("Total monthly spend cap in cents"),
396
- computeCapCents: z.number().int().nonnegative().optional().describe("Compute spend cap in cents"),
397
- storageCapCents: z.number().int().nonnegative().optional().describe("Storage spend cap in cents"),
398
- alertThresholdPct: z.number().int().min(1).max(100).optional().describe("Percent of cap that triggers an alert (1-100)")
399
- }, async (caps) => {
400
- const body = {};
401
- for (const [k, v] of Object.entries(caps)) {
402
- if (v !== undefined)
403
- body[k] = v;
404
- }
405
- return jsonResponse(await apiRequest("PATCH", "/api/billing/caps", body));
406
- });
407
346
  }
408
347
 
409
348
  // src/tools/contracts.ts
410
- import { generateContractInterface } from "@secondlayer/scaffold";
411
349
  import { z as z2 } from "zod/v4";
412
350
  function registerContractTools(server, clientProvider = getClient) {
413
351
  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.', {
@@ -417,7 +355,7 @@ function registerContractTools(server, clientProvider = getClient) {
417
355
  limit: z2.number().optional().describe("Page size, 1–500 (default 100)"),
418
356
  cursor: z2.string().optional().describe("Opaque cursor from a prior response's next_cursor")
419
357
  }, async (params) => jsonResponse(await clientProvider().contracts.list(params)));
420
- defineTool(server, "get_contract_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. Feed the ABI into scaffold_from_abi or generate a typed client.", {
358
+ defineTool(server, "get_contract_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 scaffold_from_contract.", {
421
359
  contractId: z2.string().describe("Fully qualified contract id (e.g. SP….amm-pool-v2-01)")
422
360
  }, async ({ contractId }) => {
423
361
  const contract = await clientProvider().contracts.get(contractId, {
@@ -431,43 +369,12 @@ function registerContractTools(server, clientProvider = getClient) {
431
369
  }
432
370
  }, true);
433
371
  });
434
- defineTool(server, "generate_contract_interface", "Generate a typed TypeScript contract-client interface (typed methods + map/var/constant readers) from a deployed contract's ABI (fetched from the registry). Returns not_found if the contract isn't in the registry.", {
435
- contractId: z2.string().describe("Fully qualified contract id (e.g. SP….amm-pool-v2-01)")
436
- }, async ({ contractId }) => {
437
- const c = await clientProvider().contracts.get(contractId, {
438
- includeAbi: true
439
- });
440
- if (!c || !c.abi) {
441
- return jsonResponse({
442
- error: {
443
- type: "not_found",
444
- status: 404,
445
- message: `Contract not in registry: ${contractId}`
446
- }
447
- }, true);
448
- }
449
- const [address, contractName] = contractId.split(".");
450
- const name = (contractName ?? contractId).replace(/[^a-zA-Z0-9]/g, "_");
451
- const code = generateContractInterface([
452
- {
453
- name,
454
- address,
455
- contractName: contractName ?? "",
456
- abi: c.abi
457
- }
458
- ]);
459
- return { content: [{ type: "text", text: code }] };
460
- });
461
372
  }
462
373
 
463
374
  // src/tools/index.ts
464
- import { DECODED_EVENT_TYPES as DECODED_EVENT_TYPES2 } from "@secondlayer/shared";
465
- import {
466
- INDEX_CODEGEN_TABLES,
467
- generateIndexSchema
468
- } from "@secondlayer/subgraphs";
375
+ import { DECODED_EVENT_TYPES } from "@secondlayer/shared";
469
376
  import { z as z3 } from "zod/v4";
470
- var INDEX_EVENT_TYPES = DECODED_EVENT_TYPES2;
377
+ var INDEX_EVENT_TYPES = DECODED_EVENT_TYPES;
471
378
  var rangeFilters = {
472
379
  contractId: z3.string().optional().describe("Filter by contract id"),
473
380
  fromHeight: z3.number().optional().describe("Start block height (inclusive)"),
@@ -481,7 +388,6 @@ var heightFilters = {
481
388
  cursor: rangeFilters.cursor,
482
389
  limit: rangeFilters.limit
483
390
  };
484
- var notFound = (message) => jsonResponse({ error: { type: "not_found", status: 404, message } }, true);
485
391
  function registerIndexTools(server, clientProvider = getClient) {
486
392
  defineTool(server, "index_ft_transfers", "List decoded SIP-010 fungible-token transfers from the Index (L2 decoded layer). Anonymous reads allowed (free-tier API keys are rejected — Build+ required).", {
487
393
  ...rangeFilters,
@@ -508,54 +414,13 @@ function registerIndexTools(server, clientProvider = getClient) {
508
414
  sender: z3.string().optional().describe("Filter by caller principal"),
509
415
  trait: z3.string().optional().describe("Match contracts conforming to a trait/standard (e.g. sip-010). Mutually exclusive with contractId.")
510
416
  }, async (params) => jsonResponse(await clientProvider().index.contractCalls.list(params)));
511
- defineTool(server, "index_canonical", "List the canonical Stacks block sequence from the Index (height + hash). Anonymous reads allowed (free-tier keys rejected).", { ...heightFilters }, async (params) => jsonResponse(await clientProvider().index.canonical.list(params)));
512
417
  defineTool(server, "index_blocks", "List decoded blocks from the Index. Anonymous reads allowed (free-tier keys rejected).", { ...heightFilters }, async (params) => jsonResponse(await clientProvider().index.blocks.list(params)));
513
- defineTool(server, "index_block", "Get a single block from the Index by height or block hash. Returns not_found if unknown.", {
514
- ref: z3.string().describe("Block height (digits) or block hash (0x… string)")
515
- }, async ({ ref }) => {
516
- const block = await clientProvider().index.blocks.get(/^\d+$/.test(ref) ? Number(ref) : ref);
517
- return block ? jsonResponse(block) : notFound(`No block for ref ${ref}`);
518
- });
519
418
  defineTool(server, "index_transactions", "List decoded transactions from the Index. Filter by type, sender, or contract. Anonymous reads allowed (free-tier keys rejected).", {
520
419
  ...rangeFilters,
521
420
  type: z3.string().optional().describe("Filter by transaction type"),
522
421
  sender: z3.string().optional().describe("Filter by sender principal")
523
422
  }, async (params) => jsonResponse(await clientProvider().index.transactions.list(params)));
524
- defineTool(server, "index_transaction", "Get a single transaction from the Index by tx_id. Returns not_found if unknown.", { txId: z3.string().describe("Transaction id (0x… hash)") }, async ({ txId }) => {
525
- const tx = await clientProvider().index.transactions.get(txId);
526
- return tx ? jsonResponse(tx) : notFound(`No transaction for ${txId}`);
527
- });
528
- defineTool(server, "index_transaction_proof", "Fetch a transaction's inclusion proof (raw tx + signed Nakamoto block header + merkle path) so it can be verified trustlessly client-side with the SDK's verifyTransactionProof. Returns not_found if the tx/block is unknown; a 503 means the proof can't be assembled on this deployment right now (PROOF_TX_SET_INCOMPLETE, or PROOF_NODE_UNAVAILABLE when the stacks-node header source isn't configured).", { txId: z3.string().describe("Transaction id (0x… hash)") }, async ({ txId }) => {
529
- const proof = await clientProvider().index.transactions.getProof(txId);
530
- return proof ? jsonResponse(proof) : notFound(`No proof available for ${txId}`);
531
- });
532
- defineTool(server, "index_stacking", "List decoded PoX-4 stacking actions from the Index (stack-stx, delegate-stx, etc.). Anonymous reads allowed (free-tier keys rejected).", {
533
- ...heightFilters,
534
- functionName: z3.string().optional().describe("Filter by PoX function name"),
535
- stacker: z3.string().optional().describe("Filter by stacker principal"),
536
- caller: z3.string().optional().describe("Filter by caller principal")
537
- }, async (params) => jsonResponse(await clientProvider().index.stacking.list(params)));
538
- defineTool(server, "index_mempool", "List pending (unconfirmed) transactions from the Index mempool. Sequence-cursor paginated (no height range). Anonymous reads allowed (free-tier keys rejected).", {
539
- sender: z3.string().optional().describe("Filter by sender principal"),
540
- type: z3.string().optional().describe("Filter by transaction type"),
541
- contractId: z3.string().optional().describe("Filter to pending calls to a single contract"),
542
- cursor: z3.string().optional().describe("Opaque cursor from a prior response's next_cursor"),
543
- limit: z3.number().optional().describe("Max rows for this page")
544
- }, async (params) => jsonResponse(await clientProvider().index.mempool.list(params)));
545
- defineTool(server, "index_mempool_tx", "Get a single pending transaction from the Index mempool by tx_id. Returns not_found once it is mined or dropped.", { txId: z3.string().describe("Transaction id (0x… hash)") }, async ({ txId }) => {
546
- const tx = await clientProvider().index.mempool.get(txId);
547
- return tx ? jsonResponse(tx) : notFound(`No pending tx for ${txId}`);
548
- });
549
423
  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()));
550
- defineTool(server, "index_usage", "Your own Index consumption (decoded events today + this month) and tier limits. Requires a Build+ API key (anonymous reads can't report usage).", {}, async () => jsonResponse(await clientProvider().index.usage()));
551
- defineTool(server, "index_codegen", `Generate a typed schema (Prisma, Kysely, Drizzle, or JSON-Schema) for the public Index domain tables so they can be mirrored into a BYO database with full types. Returns the schema as text. Tables: ${INDEX_CODEGEN_TABLES.join(", ")}.`, {
552
- target: z3.enum(["prisma", "kysely", "drizzle", "json-schema"]).optional().describe("Output target (default kysely)"),
553
- tables: z3.array(z3.string()).optional().describe("Subset of Index tables (default: all)"),
554
- schemaName: z3.string().optional().describe("Postgres schema to qualify table names with")
555
- }, async ({ target = "kysely", tables, schemaName }) => {
556
- const out = generateIndexSchema(target, { tables, schemaName });
557
- return { content: [{ type: "text", text: out }] };
558
- });
559
424
  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.", {
560
425
  requests: z3.array(z3.object({
561
426
  path: z3.string().describe("Public /v1 read path"),
@@ -564,49 +429,11 @@ function registerIndexTools(server, clientProvider = getClient) {
564
429
  }, async (params) => jsonResponse(await clientProvider().batch(params.requests)));
565
430
  }
566
431
 
567
- // src/tools/projects.ts
568
- import { z as z4 } from "zod/v4";
569
- function registerProjectTools(server, clientProvider = getClient) {
570
- defineTool(server, "project_list", "List the account's projects. Requires an account-level (owner) API key.", {}, async () => jsonResponse(await clientProvider().projects.list()));
571
- defineTool(server, "project_get", "Get a single project by slug.", { slug: z4.string().describe("Project slug") }, async ({ slug }) => jsonResponse(await clientProvider().projects.get(slug)));
572
- defineTool(server, "project_create", "Create a project. The slug is derived from the name when omitted. Requires an account-level (owner) API key.", {
573
- name: z4.string().describe("Project name"),
574
- slug: z4.string().optional().describe("URL slug (auto-derived from name if omitted)"),
575
- network: z4.string().optional().describe("Network (e.g. mainnet, testnet)"),
576
- nodeRpc: z4.string().optional().describe("Custom node RPC URL")
577
- }, async ({ name, slug, network, nodeRpc }) => jsonResponse(await clientProvider().projects.create({
578
- name,
579
- slug,
580
- network,
581
- nodeRpc
582
- })));
583
- defineTool(server, "project_update", "Update a project. `slug` selects the project; `newSlug` renames it. Requires an account-level (owner) API key.", {
584
- slug: z4.string().describe("Slug of the project to update"),
585
- newSlug: z4.string().optional().describe("New slug (renames the project)"),
586
- name: z4.string().optional().describe("New display name"),
587
- network: z4.string().optional().describe("Network (e.g. mainnet, testnet)"),
588
- nodeRpc: z4.string().optional().describe("Custom node RPC URL"),
589
- settings: z4.record(z4.string(), z4.unknown()).optional().describe("Arbitrary project settings to merge")
590
- }, async ({ slug, newSlug, name, network, nodeRpc, settings }) => jsonResponse(await clientProvider().projects.update(slug, {
591
- ...newSlug !== undefined ? { slug: newSlug } : {},
592
- ...name !== undefined ? { name } : {},
593
- ...network !== undefined ? { network } : {},
594
- ...nodeRpc !== undefined ? { nodeRpc } : {},
595
- ...settings !== undefined ? { settings } : {}
596
- })));
597
- defineTool(server, "project_delete", "Delete a project permanently. The account's last remaining project cannot be deleted.", { slug: z4.string().describe("Project slug") }, async ({ slug }) => jsonResponse(await clientProvider().projects.delete(slug)));
598
- defineTool(server, "project_team_list", "List a project's team members and pending invitations.", { slug: z4.string().describe("Project slug") }, async ({ slug }) => jsonResponse(await clientProvider().projects.team(slug)));
599
- }
600
-
601
432
  // src/tools/scaffold.ts
602
- import {
603
- generateSubgraphCode,
604
- generateTraitSubgraph
605
- } from "@secondlayer/scaffold";
606
- import { TRAIT_STANDARDS as TRAIT_STANDARDS2 } from "@secondlayer/stacks/clarity";
607
- import { z as z5 } from "zod/v4";
608
- async function fetchAbi(contractId) {
609
- const contract = await getClient().contracts.get(contractId, {
433
+ import { generateSubgraphCode } from "@secondlayer/scaffold";
434
+ import { z as z4 } from "zod/v4";
435
+ async function fetchAbi(clientProvider, contractId) {
436
+ const contract = await clientProvider().contracts.get(contractId, {
610
437
  includeAbi: true
611
438
  });
612
439
  if (!contract)
@@ -617,134 +444,26 @@ async function fetchAbi(contractId) {
617
444
  }
618
445
  return { functions: abi.functions ?? [], maps: abi.maps ?? [] };
619
446
  }
620
- function registerScaffoldTools(server) {
621
- defineTool(server, "scaffold_from_trait", "Generate a deploy-ready subgraph scaffold that indexes EVERY contract conforming to a SIP trait (no specific contract needed) — sip-009 → an nft_transfer source, sip-010/sip-013 → ft_transfer. Use scaffold_from_contract/abi instead when targeting one contract. See the secondlayer://traits resource for valid trait ids.", {
622
- trait: z5.enum(TRAIT_STANDARDS2).describe("SIP standard to index (sip-009 | sip-010 | sip-013)"),
623
- subgraphName: z5.string().optional().describe("Override the subgraph name (defaults to <trait>-transfers)")
624
- }, async ({ trait, subgraphName }) => {
625
- const code = generateTraitSubgraph({ trait, name: subgraphName });
626
- return { content: [{ type: "text", text: code }] };
627
- });
447
+ function registerScaffoldTools(server, clientProvider = getClient) {
628
448
  defineTool(server, "scaffold_from_contract", "Generate a subgraph scaffold from a deployed Stacks contract. Fetches the ABI automatically.", {
629
- contractId: z5.string().describe("Fully qualified contract ID (e.g. SP102V8P0F7JX67ARQ77WEA3D3CFB5XW39REDT0AM.amm-pool-v2-01)"),
630
- subgraphName: z5.string().optional().describe("Override the subgraph name (defaults to contract name)")
449
+ contractId: z4.string().describe("Fully qualified contract ID (e.g. SP102V8P0F7JX67ARQ77WEA3D3CFB5XW39REDT0AM.amm-pool-v2-01)"),
450
+ subgraphName: z4.string().optional().describe("Override the subgraph name (defaults to contract name)")
631
451
  }, async ({ contractId, subgraphName }) => {
632
- const { functions, maps } = await fetchAbi(contractId);
452
+ const { functions, maps } = await fetchAbi(clientProvider, contractId);
633
453
  const code = generateSubgraphCode(contractId, functions, subgraphName, maps);
634
454
  return { content: [{ type: "text", text: code }] };
635
455
  });
636
- defineTool(server, "scaffold_from_abi", "Generate a subgraph scaffold from a provided ABI JSON. Use when you already have the ABI.", {
637
- abi: z5.string().describe("ABI JSON string (the full contract ABI object)"),
638
- contractId: z5.string().describe("Fully qualified contract ID"),
639
- subgraphName: z5.string().optional().describe("Override the subgraph name")
640
- }, async ({ abi, contractId, subgraphName }) => {
641
- let parsed;
642
- try {
643
- parsed = JSON.parse(abi);
644
- } catch {
645
- return {
646
- content: [{ type: "text", text: "Invalid ABI JSON" }],
647
- isError: true
648
- };
649
- }
650
- const code = generateSubgraphCode(contractId, parsed.functions ?? [], subgraphName, parsed.maps ?? []);
651
- return { content: [{ type: "text", text: code }] };
652
- });
653
456
  }
654
457
 
655
458
  // src/tools/streams.ts
656
- import { AuthError } from "@secondlayer/sdk";
657
- import { DECODED_EVENT_TYPES as DECODED_EVENT_TYPES3 } from "@secondlayer/shared";
658
- import { z as z6 } from "zod/v4";
659
- var STREAMS_EVENT_TYPES = DECODED_EVENT_TYPES3;
660
- async function withStreamsAuthHint(fn) {
661
- try {
662
- return await fn();
663
- } catch (err) {
664
- if (err instanceof AuthError) {
665
- throw Object.assign(new Error(err.message + keyHint), { status: 401 });
666
- }
667
- throw err;
668
- }
669
- }
670
459
  function registerStreamsTools(server, clientProvider = getClient) {
671
- defineTool(server, "streams_tip", "Get the current Streams chain tip (latest processed block + lag). Streams requires an API key (SL_API_KEY).", {}, async () => withStreamsAuthHint(async () => jsonResponse(await clientProvider().streams.tip())));
672
- defineTool(server, "streams_events", "List raw chain events from the Streams firehose. Streams requires an API key (SL_API_KEY). Filter by event types, principals, contract, asset, or block range; page with cursor.", {
673
- types: z6.array(z6.enum(STREAMS_EVENT_TYPES)).optional().describe("Event types to include"),
674
- notTypes: z6.array(z6.enum(STREAMS_EVENT_TYPES)).optional().describe("Event types to exclude (applied after types)"),
675
- contractId: z6.string().optional().describe("Filter by contract id"),
676
- sender: z6.string().optional().describe("Filter by sender principal"),
677
- recipient: z6.string().optional().describe("Filter by recipient principal"),
678
- assetIdentifier: z6.string().optional().describe("Filter by asset identifier"),
679
- fromHeight: z6.number().optional().describe("Start block height (inclusive)"),
680
- toHeight: z6.number().optional().describe("End block height (inclusive)"),
681
- cursor: z6.string().optional().describe("Opaque cursor from a prior response"),
682
- limit: z6.number().optional().describe("Max events for this page")
683
- }, async (params) => withStreamsAuthHint(async () => jsonResponse(await clientProvider().streams.events.list(params))));
684
- defineTool(server, "streams_consume", "Consume a bounded, reorg-aware run of Streams events from a cursor. Walks up to maxPages pages and returns the events, any reorgs observed, and a resume `cursor` to pass back as fromCursor next call — the agent-native consume/resume primitive. Streams requires an API key (SL_API_KEY).", {
685
- fromCursor: z6.string().optional().describe("Resume cursor from a prior consume (omit to start at genesis)"),
686
- types: z6.array(z6.enum(STREAMS_EVENT_TYPES)).optional().describe("Event types to include"),
687
- notTypes: z6.array(z6.enum(STREAMS_EVENT_TYPES)).optional().describe("Event types to exclude"),
688
- contractId: z6.string().optional().describe("Filter by contract id"),
689
- sender: z6.string().optional().describe("Filter by sender principal"),
690
- recipient: z6.string().optional().describe("Filter by recipient principal"),
691
- assetIdentifier: z6.string().optional().describe("Filter by asset identifier"),
692
- batchSize: z6.number().optional().describe("Events per page (1–1000, default 100)"),
693
- maxPages: z6.number().optional().describe("Max pages to walk this call (1–20, default 5)"),
694
- finalizedOnly: z6.boolean().optional().describe("Only emit finalized events; skip reorg handling")
695
- }, async (params) => withStreamsAuthHint(async () => {
696
- const maxPages = Math.min(Math.max(params.maxPages ?? 5, 1), 20);
697
- const batchSize = Math.min(Math.max(params.batchSize ?? 100, 1), 1000);
698
- const events = [];
699
- const reorgs = [];
700
- const result = await clientProvider().streams.events.consume({
701
- fromCursor: params.fromCursor ?? null,
702
- mode: "bounded",
703
- finalizedOnly: params.finalizedOnly,
704
- types: params.types,
705
- notTypes: params.notTypes,
706
- contractId: params.contractId,
707
- sender: params.sender,
708
- recipient: params.recipient,
709
- assetIdentifier: params.assetIdentifier,
710
- batchSize,
711
- maxPages,
712
- onBatch: (batch) => {
713
- events.push(...batch);
714
- },
715
- onReorg: (reorg) => {
716
- reorgs.push(reorg);
717
- }
718
- });
719
- return jsonResponse({
720
- events,
721
- reorgs,
722
- cursor: result.cursor,
723
- pages: result.pages
724
- });
725
- }));
726
- defineTool(server, "streams_event_by_txid", "List all Streams events emitted by a single transaction. Streams requires an API key (SL_API_KEY).", { txId: z6.string().describe("Transaction id (0x… hash)") }, async ({ txId }) => withStreamsAuthHint(async () => jsonResponse(await clientProvider().streams.events.byTxId(txId))));
727
- defineTool(server, "streams_block_events", "List all Streams events in a single block, by height or block hash. Streams requires an API key (SL_API_KEY).", {
728
- heightOrHash: z6.string().describe("Block height (digits) or block hash (0x… string)")
729
- }, async ({ heightOrHash }) => withStreamsAuthHint(async () => jsonResponse(await clientProvider().streams.blocks.events(/^\d+$/.test(heightOrHash) ? Number(heightOrHash) : heightOrHash))));
730
- defineTool(server, "streams_reorgs", "List chain reorgs observed by Streams since a cursor. Streams requires an API key (SL_API_KEY).", {
731
- since: z6.string().describe("Cursor to list reorgs since (block:index or ISO timestamp)"),
732
- limit: z6.number().optional().describe("Max reorgs to return")
733
- }, async (params) => withStreamsAuthHint(async () => jsonResponse(await clientProvider().streams.reorgs.list(params))));
734
- defineTool(server, "streams_canonical", "Get the canonical block at a given height from Streams (height + hashes + is_canonical). Streams requires an API key (SL_API_KEY).", { height: z6.number().describe("Block height") }, async ({ height }) => withStreamsAuthHint(async () => jsonResponse(await clientProvider().streams.canonical(height))));
735
- defineTool(server, "streams_usage", "Your own Streams consumption (events today + this month) and tier limits (rate limit, retention). Streams requires an API key (SL_API_KEY).", {}, async () => withStreamsAuthHint(async () => jsonResponse(await clientProvider().streams.usage())));
736
- defineTool(server, "streams_dumps", "List the Streams bulk parquet dumps manifest — coverage range, latest_finalized_cursor, and per-file metadata (block range, row count, size, sha256, signed URL). This is the cold backfill path for downloading all raw data; fetch the file URLs directly (e.g. with DuckDB). Requires the dumps base URL to be configured (SL_STREAMS_DUMPS_URL).", {}, async () => jsonResponse(await clientProvider().streams.dumps.list()));
460
+ defineTool(server, "streams_dumps", "List the Streams bulk parquet dumps manifest — coverage range, latest_finalized_cursor, and per-file metadata (block range, row count, size, sha256, signed URL). This is the cold backfill path for downloading all raw data; fetch the file URLs directly (e.g. with DuckDB). Requires the dumps base URL to be configured (SL_STREAMS_DUMPS_URL). Live Streams reads (tip, events, consume) are REST-only: see /v1/streams/* in the OpenAPI spec.", {}, async () => jsonResponse(await clientProvider().streams.dumps.list()));
737
461
  }
738
462
 
739
463
  // src/tools/subgraphs.ts
740
464
  import { bundleSubgraphCode } from "@secondlayer/bundler";
741
465
  import { ByoBreakingChangeError } from "@secondlayer/sdk";
742
- import {
743
- generateDrizzleSchema,
744
- generateKyselySchema,
745
- generatePrismaSchema
746
- } from "@secondlayer/subgraphs";
747
- import { z as z7 } from "zod/v4";
466
+ import { z as z5 } from "zod/v4";
748
467
  function registerSubgraphTools(server, clientProvider = getClient) {
749
468
  defineTool(server, "subgraphs_list", "List all deployed subgraphs. Returns summary fields only, including visibility — public subgraphs are anon-readable at /v1/subgraphs/<name>.", {}, async () => {
750
469
  const { data } = await clientProvider().subgraphs.list();
@@ -757,38 +476,22 @@ function registerSubgraphTools(server, clientProvider = getClient) {
757
476
  ]
758
477
  };
759
478
  });
760
- defineTool(server, "subgraphs_get", "Get full details of a subgraph including schema, health, and table columns.", { name: z7.string().describe("Subgraph name") }, async ({ name }) => {
479
+ defineTool(server, "subgraphs_get", "Get full details of a subgraph including schema, health, and table columns.", { name: z5.string().describe("Subgraph name") }, async ({ name }) => {
761
480
  const detail = await clientProvider().subgraphs.get(name);
762
481
  return {
763
482
  content: [{ type: "text", text: JSON.stringify(detail, null, 2) }]
764
483
  };
765
484
  });
766
- defineTool(server, "subgraphs_spec", "Get generated API documentation for a subgraph. Defaults to compact agent schema; supports OpenAPI JSON and Markdown.", {
767
- name: z7.string().describe("Subgraph name"),
768
- format: z7.enum(["agent", "openapi", "markdown"]).optional().describe("Spec format to return. Defaults to agent."),
769
- serverUrl: z7.string().optional().describe("Override the server URL embedded in generated docs.")
770
- }, async ({ name, format = "agent", serverUrl }) => {
771
- const options = serverUrl ? { serverUrl } : undefined;
772
- const spec = format === "openapi" ? await clientProvider().subgraphs.openapi(name, options) : format === "markdown" ? await clientProvider().subgraphs.markdown(name, options) : await clientProvider().subgraphs.schema(name, options);
773
- return {
774
- content: [
775
- {
776
- type: "text",
777
- text: typeof spec === "string" ? spec : JSON.stringify(spec, null, 2)
778
- }
779
- ]
780
- };
781
- });
782
485
  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. Fetch one row by id with {"_id": "<id>"}. Public subgraphs are also keyless 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.', {
783
- name: z7.string().describe("Subgraph name"),
784
- table: z7.string().describe("Table name"),
785
- filters: z7.record(z7.string(), z7.string()).optional().describe('Column filters — plain values or with operators (e.g. {"amount.gte": "1000", "sender": "SP..."})'),
786
- sort: z7.string().optional().describe("Column to sort by"),
787
- order: z7.enum(["asc", "desc"]).optional().describe("Sort order"),
788
- limit: z7.number().max(200).optional().describe("Max rows (default 50, max 200)"),
789
- offset: z7.number().optional().describe("Offset for pagination"),
790
- fields: z7.string().optional().describe('Comma-separated column list to return (e.g. "sender,amount")'),
791
- count: z7.boolean().optional().describe("If true, return row count instead of rows")
486
+ name: z5.string().describe("Subgraph name"),
487
+ table: z5.string().describe("Table name"),
488
+ filters: z5.record(z5.string(), z5.string()).optional().describe('Column filters — plain values or with operators (e.g. {"amount.gte": "1000", "sender": "SP..."})'),
489
+ sort: z5.string().optional().describe("Column to sort by"),
490
+ order: z5.enum(["asc", "desc"]).optional().describe("Sort order"),
491
+ limit: z5.number().max(200).optional().describe("Max rows (default 50, max 200)"),
492
+ offset: z5.number().optional().describe("Offset for pagination"),
493
+ fields: z5.string().optional().describe('Comma-separated column list to return (e.g. "sender,amount")'),
494
+ count: z5.boolean().optional().describe("If true, return row count instead of rows")
792
495
  }, async ({
793
496
  name,
794
497
  table,
@@ -820,25 +523,10 @@ function registerSubgraphTools(server, clientProvider = getClient) {
820
523
  content: [{ type: "text", text: JSON.stringify(result, null, 2) }]
821
524
  };
822
525
  });
823
- defineTool(server, "subgraphs_aggregate", `Compute scalar aggregates over a subgraph table's filtered rows. Supports count, countDistinct, and sum/min/max (numeric columns only — uint/int plus the system _block_height). Filters use the same grammar as subgraphs_query (e.g. {"amount.gte": "1000"}). sum/min/max come back as lossless strings; counts as numbers. With no aggregate requested, returns the row count.`, {
824
- name: z7.string().describe("Subgraph name"),
825
- table: z7.string().describe("Table name"),
826
- filters: z7.record(z7.string(), z7.string()).optional().describe('Column filters — plain values or with operators (e.g. {"amount.gte": "1000", "sender": "SP..."})'),
827
- count: z7.boolean().optional().describe("Include COUNT(*) of matching rows"),
828
- countDistinct: z7.array(z7.string()).optional().describe("Columns to count distinct values of"),
829
- sum: z7.array(z7.string()).optional().describe("Numeric columns to sum (lossless string result)"),
830
- min: z7.array(z7.string()).optional().describe("Numeric columns to take the minimum of"),
831
- max: z7.array(z7.string()).optional().describe("Numeric columns to take the maximum of")
832
- }, async ({ name, table, filters, count, countDistinct, sum, min, max }) => {
833
- const result = await clientProvider().subgraphs.queryTableAggregate(name, table, { filters, count, countDistinct, sum, min, max });
834
- return {
835
- content: [{ type: "text", text: JSON.stringify(result, null, 2) }]
836
- };
837
- });
838
- defineTool(server, "subgraphs_reindex", "Reindex a subgraph from a specific block range. Returns an operationId — poll subgraphs_operation to track progress to completion.", {
839
- name: z7.string().describe("Subgraph name"),
840
- fromBlock: z7.number().optional().describe("Start block (defaults to beginning)"),
841
- toBlock: z7.number().optional().describe("End block (defaults to latest)")
526
+ defineTool(server, "subgraphs_reindex", "Reindex a subgraph from a specific block range. Returns an operationId — check subgraphs_get (health) or the REST operations endpoint to track progress to completion.", {
527
+ name: z5.string().describe("Subgraph name"),
528
+ fromBlock: z5.number().optional().describe("Start block (defaults to beginning)"),
529
+ toBlock: z5.number().optional().describe("End block (defaults to latest)")
842
530
  }, async ({ name, fromBlock, toBlock }) => {
843
531
  const result = await clientProvider().subgraphs.reindex(name, {
844
532
  fromBlock,
@@ -848,19 +536,10 @@ function registerSubgraphTools(server, clientProvider = getClient) {
848
536
  content: [{ type: "text", text: JSON.stringify(result, null, 2) }]
849
537
  };
850
538
  });
851
- defineTool(server, "subgraphs_operation", "Check reindex/backfill progress. With operationId, returns that operation's status (poll until status is completed/failed/cancelled); without it, lists recent operations for the subgraph.", {
852
- name: z7.string().describe("Subgraph name"),
853
- operationId: z7.string().optional().describe("Operation id from reindex/backfill/stop; omit to list recent operations")
854
- }, async ({ name, operationId }) => {
855
- const result = operationId ? await clientProvider().subgraphs.getOperation(name, operationId) : await clientProvider().subgraphs.operations(name);
856
- return {
857
- content: [{ type: "text", text: JSON.stringify(result, null, 2) }]
858
- };
859
- });
860
- 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 — poll subgraphs_operation to track progress.", {
861
- name: z7.string().describe("Subgraph name"),
862
- fromBlock: z7.number().int().nonnegative().describe("Start block (inclusive)"),
863
- toBlock: z7.number().int().nonnegative().describe("End block (inclusive)")
539
+ 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_get (health) or the REST operations endpoint to track progress.", {
540
+ name: z5.string().describe("Subgraph name"),
541
+ fromBlock: z5.number().int().nonnegative().describe("Start block (inclusive)"),
542
+ toBlock: z5.number().int().nonnegative().describe("End block (inclusive)")
864
543
  }, async ({ name, fromBlock, toBlock }) => {
865
544
  const result = await clientProvider().subgraphs.backfill(name, {
866
545
  fromBlock,
@@ -870,17 +549,17 @@ function registerSubgraphTools(server, clientProvider = getClient) {
870
549
  content: [{ type: "text", text: JSON.stringify(result, null, 2) }]
871
550
  };
872
551
  });
873
- defineTool(server, "subgraphs_stop", "Cancel an in-flight reindex or backfill operation for a subgraph. Returns the stop request status; poll subgraphs_operation to confirm it reaches a terminal state.", { name: z7.string().describe("Subgraph name") }, async ({ name }) => {
552
+ defineTool(server, "subgraphs_stop", "Cancel an in-flight reindex or backfill operation for a subgraph. Returns the stop request status; check subgraphs_get (health) or the REST operations endpoint to confirm it reaches a terminal state.", { name: z5.string().describe("Subgraph name") }, async ({ name }) => {
874
553
  const result = await clientProvider().subgraphs.stop(name);
875
554
  return {
876
555
  content: [{ type: "text", text: JSON.stringify(result, null, 2) }]
877
556
  };
878
557
  });
879
558
  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.", {
880
- name: z7.string().describe("Subgraph name"),
881
- limit: z7.number().int().positive().optional().describe("Max gaps to return"),
882
- offset: z7.number().int().nonnegative().optional().describe("Pagination offset"),
883
- resolved: z7.boolean().optional().describe("Filter by resolved state (omit for unresolved only)")
559
+ name: z5.string().describe("Subgraph name"),
560
+ limit: z5.number().int().positive().optional().describe("Max gaps to return"),
561
+ offset: z5.number().int().nonnegative().optional().describe("Pagination offset"),
562
+ resolved: z5.boolean().optional().describe("Filter by resolved state (omit for unresolved only)")
884
563
  }, async ({ name, limit, offset, resolved }) => {
885
564
  const result = await clientProvider().subgraphs.gaps(name, {
886
565
  limit,
@@ -891,16 +570,16 @@ function registerSubgraphTools(server, clientProvider = getClient) {
891
570
  content: [{ type: "text", text: JSON.stringify(result, null, 2) }]
892
571
  };
893
572
  });
894
- defineTool(server, "subgraphs_delete", "Delete a subgraph permanently.", { name: z7.string().describe("Subgraph name") }, async ({ name }) => {
573
+ defineTool(server, "subgraphs_delete", "Delete a subgraph permanently.", { name: z5.string().describe("Subgraph name") }, async ({ name }) => {
895
574
  const result = await clientProvider().subgraphs.delete(name);
896
575
  return { content: [{ type: "text", text: result.message }] };
897
576
  });
898
577
  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. Set databaseUrl to deploy to your own Postgres (BYO data plane) — the server verifies the connection first; with dryRun it returns the DDL + grant script. A breaking BYO schema change is refused and returns a migration plan (drop + rebuild DDL) instead of deploying. Visibility defaults: managed deploys are public (anon-readable at /v1/subgraphs/<name>, name claimed in the global public namespace), BYO deploys are private. Call `subgraphs_reindex` separately if you need a forced reindex.", {
899
- code: z7.string().describe("TypeScript source code containing a defineSubgraph() call"),
900
- startBlock: z7.number().int().nonnegative().optional().describe("Override the definition startBlock for this deploy"),
901
- databaseUrl: z7.string().optional().describe("BYO data plane: Postgres connection string to host the subgraph's schema and rows in your own database"),
902
- dryRun: z7.boolean().optional().describe("Validate and preview the deploy (schema/DDL, BYO connection) without writing changes"),
903
- visibility: z7.enum(["public", "private"]).optional().describe("Read visibility: public = anon /v1 reads + global name claim; private = owning account's key only. Defaults: managed → public, BYO → private.")
578
+ code: z5.string().describe("TypeScript source code containing a defineSubgraph() call"),
579
+ startBlock: z5.number().int().nonnegative().optional().describe("Override the definition startBlock for this deploy"),
580
+ databaseUrl: z5.string().optional().describe("BYO data plane: Postgres connection string to host the subgraph's schema and rows in your own database"),
581
+ dryRun: z5.boolean().optional().describe("Validate and preview the deploy (schema/DDL, BYO connection) without writing changes"),
582
+ visibility: z5.enum(["public", "private"]).optional().describe("Read visibility: public = anon /v1 reads + global name claim; private = owning account's key only. Defaults: managed → public, BYO → private.")
904
583
  }, async ({ code, startBlock, databaseUrl, dryRun, visibility }) => {
905
584
  const bundled = await bundleSubgraphCode(code);
906
585
  try {
@@ -934,58 +613,23 @@ function registerSubgraphTools(server, clientProvider = getClient) {
934
613
  throw err;
935
614
  }
936
615
  });
937
- defineTool(server, "subgraphs_publish", "Make a subgraph publicly readable at /v1/subgraphs/<name> — anyone (or any agent) can read it without a key. Claims the name in the global public namespace; fails with PUBLIC_NAME_TAKEN if another account holds it.", { name: z7.string().describe("Subgraph name") }, async ({ name }) => {
616
+ defineTool(server, "subgraphs_publish", "Make a subgraph publicly readable at /v1/subgraphs/<name> — anyone (or any agent) can read it without a key. Claims the name in the global public namespace; fails with PUBLIC_NAME_TAKEN if another account holds it.", { name: z5.string().describe("Subgraph name") }, async ({ name }) => {
938
617
  const result = await clientProvider().subgraphs.publish(name);
939
618
  return {
940
619
  content: [{ type: "text", text: JSON.stringify(result, null, 2) }]
941
620
  };
942
621
  });
943
- defineTool(server, "subgraphs_unpublish", "Make a subgraph private again — /v1 reads then require the owning account's bearer key, and the global public name claim is released.", { name: z7.string().describe("Subgraph name") }, async ({ name }) => {
622
+ defineTool(server, "subgraphs_unpublish", "Make a subgraph private again — /v1 reads then require the owning account's bearer key, and the global public name claim is released.", { name: z5.string().describe("Subgraph name") }, async ({ name }) => {
944
623
  const result = await clientProvider().subgraphs.unpublish(name);
945
624
  return {
946
625
  content: [{ type: "text", text: JSON.stringify(result, null, 2) }]
947
626
  };
948
627
  });
949
- defineTool(server, "subgraphs_read_source", "Fetch the deployed TypeScript source of a subgraph (plus its stored version). Returns a readOnly payload for subgraphs deployed before source capture — in that case the caller should redeploy via CLI before editing.", { name: z7.string().describe("Subgraph name") }, async ({ name }) => {
950
- const source = await clientProvider().subgraphs.getSource(name);
951
- return {
952
- content: [{ type: "text", text: JSON.stringify(source, null, 2) }]
953
- };
954
- });
955
- defineTool(server, "subgraphs_codegen", "Generate a typed ORM schema (Prisma, Drizzle, or Kysely) for a subgraph's tables so they can be queried from a BYO database. Pass either `code` (defineSubgraph source) or `name` (a deployed subgraph — its captured source is used). Returns the schema as text.", {
956
- code: z7.string().optional().describe("defineSubgraph() source (mutually exclusive with name)"),
957
- name: z7.string().optional().describe("Deployed subgraph name (mutually exclusive with code)"),
958
- target: z7.enum(["prisma", "drizzle", "kysely"]).optional().describe("ORM target (default prisma)"),
959
- schemaName: z7.string().optional().describe("Postgres schema name (defaults to subgraph_<name>)")
960
- }, async ({ code, name, target = "prisma", schemaName }) => {
961
- if (code && name || !code && !name) {
962
- throw new Error("Provide exactly one of `code` or `name`.");
963
- }
964
- let source = code;
965
- if (name) {
966
- const stored = await clientProvider().subgraphs.getSource(name);
967
- if (!stored.sourceCode) {
968
- throw new Error(`Subgraph "${name}" has no captured source (deployed before source capture). Redeploy it, or pass its source as \`code\`.`);
969
- }
970
- source = stored.sourceCode;
971
- }
972
- const bundled = await bundleSubgraphCode(source);
973
- const def = {
974
- name: bundled.name,
975
- version: bundled.version,
976
- description: bundled.description,
977
- sources: bundled.sources,
978
- schema: bundled.schema,
979
- handlers: {}
980
- };
981
- const out = target === "drizzle" ? generateDrizzleSchema(def, { schemaName }) : target === "kysely" ? generateKyselySchema(def, { schemaName }) : generatePrismaSchema(def, { schemaName });
982
- return { content: [{ type: "text", text: out }] };
983
- });
984
628
  }
985
629
 
986
630
  // src/tools/subscriptions.ts
987
631
  import { CHAIN_TRIGGER_TYPES } from "@secondlayer/shared";
988
- import { z as z8 } from "zod/v4";
632
+ import { z as z6 } from "zod/v4";
989
633
  function registerSubscriptionTools(server, clientProvider = getClient) {
990
634
  defineTool(server, "subscriptions_list", "List all subscriptions for the current account. Returns summary fields (no secrets).", {}, async () => {
991
635
  const { data } = await clientProvider().subscriptions.list();
@@ -993,34 +637,34 @@ function registerSubscriptionTools(server, clientProvider = getClient) {
993
637
  content: [{ type: "text", text: JSON.stringify(data, null, 2) }]
994
638
  };
995
639
  });
996
- defineTool(server, "subscriptions_get", "Get full detail for a subscription (filter, auth, retry config, circuit state).", { id: z8.string().describe("Subscription id") }, async ({ id }) => {
640
+ defineTool(server, "subscriptions_get", "Get full detail for a subscription (filter, auth, retry config, circuit state).", { id: z6.string().describe("Subscription id") }, async ({ id }) => {
997
641
  const detail = await clientProvider().subscriptions.get(id);
998
642
  return {
999
643
  content: [{ type: "text", text: JSON.stringify(detail, null, 2) }]
1000
644
  };
1001
645
  });
1002
646
  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.", {
1003
- name: z8.string().describe("Human-readable name, unique per account"),
1004
- subgraphName: z8.string().optional().describe("Subgraph to subscribe to (subgraph subscription)"),
1005
- tableName: z8.string().optional().describe("Table within the subgraph (subgraph subscription)"),
1006
- triggers: z8.array(z8.object({
1007
- type: z8.enum(CHAIN_TRIGGER_TYPES),
1008
- contractId: z8.string().optional(),
1009
- functionName: z8.string().optional(),
1010
- caller: z8.string().optional(),
1011
- sender: z8.string().optional(),
1012
- recipient: z8.string().optional(),
1013
- assetIdentifier: z8.string().optional(),
1014
- deployer: z8.string().optional(),
1015
- contractName: z8.string().optional(),
1016
- topic: z8.string().optional(),
1017
- lockedAddress: z8.string().optional(),
1018
- trait: z8.string().optional(),
1019
- minAmount: z8.union([z8.string(), z8.number()]).optional(),
1020
- maxAmount: z8.union([z8.string(), z8.number()]).optional()
647
+ name: z6.string().describe("Human-readable name, unique per account"),
648
+ subgraphName: z6.string().optional().describe("Subgraph to subscribe to (subgraph subscription)"),
649
+ tableName: z6.string().optional().describe("Table within the subgraph (subgraph subscription)"),
650
+ triggers: z6.array(z6.object({
651
+ type: z6.enum(CHAIN_TRIGGER_TYPES),
652
+ contractId: z6.string().optional(),
653
+ functionName: z6.string().optional(),
654
+ caller: z6.string().optional(),
655
+ sender: z6.string().optional(),
656
+ recipient: z6.string().optional(),
657
+ assetIdentifier: z6.string().optional(),
658
+ deployer: z6.string().optional(),
659
+ contractName: z6.string().optional(),
660
+ topic: z6.string().optional(),
661
+ lockedAddress: z6.string().optional(),
662
+ trait: z6.string().optional(),
663
+ minAmount: z6.union([z6.string(), z6.number()]).optional(),
664
+ maxAmount: z6.union([z6.string(), z6.number()]).optional()
1021
665
  })).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."),
1022
- url: z8.string().describe("Webhook URL"),
1023
- format: z8.enum([
666
+ url: z6.string().describe("Webhook URL"),
667
+ format: z6.enum([
1024
668
  "standard-webhooks",
1025
669
  "inngest",
1026
670
  "trigger",
@@ -1028,9 +672,9 @@ function registerSubscriptionTools(server, clientProvider = getClient) {
1028
672
  "cloudevents",
1029
673
  "raw"
1030
674
  ]).optional().describe("Wire format (default standard-webhooks)"),
1031
- runtime: z8.enum(["inngest", "trigger", "cloudflare", "node"]).optional().describe("Receiver runtime label (display only)"),
1032
- filter: z8.record(z8.string(), z8.unknown()).optional().describe('Scalar filter DSL, e.g. {"amount": {"gte": 100}, "sender": "SP..."}'),
1033
- authConfig: z8.record(z8.string(), z8.unknown()).optional().describe('Receiver auth sent with each delivery, e.g. {"type": "bearer", "token": "..."}')
675
+ runtime: z6.enum(["inngest", "trigger", "cloudflare", "node"]).optional().describe("Receiver runtime label (display only)"),
676
+ filter: z6.record(z6.string(), z6.unknown()).optional().describe('Scalar filter DSL, e.g. {"amount": {"gte": 100}, "sender": "SP..."}'),
677
+ authConfig: z6.record(z6.string(), z6.unknown()).optional().describe('Receiver auth sent with each delivery, e.g. {"type": "bearer", "token": "..."}')
1034
678
  }, async (input) => {
1035
679
  const res = await clientProvider().subscriptions.create(input);
1036
680
  return {
@@ -1038,12 +682,12 @@ function registerSubscriptionTools(server, clientProvider = getClient) {
1038
682
  };
1039
683
  });
1040
684
  defineTool(server, "subscriptions_update", "Patch a subscription (name, url, filter, authConfig, format, runtime, retry, timeout, concurrency).", {
1041
- id: z8.string(),
1042
- name: z8.string().optional().describe("Rename the subscription"),
1043
- url: z8.string().optional(),
1044
- filter: z8.record(z8.string(), z8.unknown()).optional(),
1045
- authConfig: z8.record(z8.string(), z8.unknown()).optional().describe("Receiver auth sent with each delivery (bearer/etc.)"),
1046
- format: z8.enum([
685
+ id: z6.string(),
686
+ name: z6.string().optional().describe("Rename the subscription"),
687
+ url: z6.string().optional(),
688
+ filter: z6.record(z6.string(), z6.unknown()).optional(),
689
+ authConfig: z6.record(z6.string(), z6.unknown()).optional().describe("Receiver auth sent with each delivery (bearer/etc.)"),
690
+ format: z6.enum([
1047
691
  "standard-webhooks",
1048
692
  "inngest",
1049
693
  "trigger",
@@ -1051,51 +695,33 @@ function registerSubscriptionTools(server, clientProvider = getClient) {
1051
695
  "cloudevents",
1052
696
  "raw"
1053
697
  ]).optional(),
1054
- runtime: z8.enum(["inngest", "trigger", "cloudflare", "node"]).nullable().optional(),
1055
- maxRetries: z8.number().int().min(0).optional(),
1056
- timeoutMs: z8.number().int().min(100).optional(),
1057
- concurrency: z8.number().int().min(1).optional()
698
+ runtime: z6.enum(["inngest", "trigger", "cloudflare", "node"]).nullable().optional(),
699
+ maxRetries: z6.number().int().min(0).optional(),
700
+ timeoutMs: z6.number().int().min(100).optional(),
701
+ concurrency: z6.number().int().min(1).optional()
1058
702
  }, async ({ id, ...patch }) => {
1059
703
  const res = await clientProvider().subscriptions.update(id, patch);
1060
704
  return {
1061
705
  content: [{ type: "text", text: JSON.stringify(res, null, 2) }]
1062
706
  };
1063
707
  });
1064
- defineTool(server, "subscriptions_pause", "Pause a subscription. Pending rows remain queued until resumed.", { id: z8.string() }, async ({ id }) => {
1065
- const res = await clientProvider().subscriptions.pause(id);
1066
- return {
1067
- content: [{ type: "text", text: JSON.stringify(res, null, 2) }]
1068
- };
1069
- });
1070
- defineTool(server, "subscriptions_resume", "Resume a paused or circuit-open subscription and reset circuit failures.", { id: z8.string() }, async ({ id }) => {
1071
- const res = await clientProvider().subscriptions.resume(id);
1072
- return {
1073
- content: [{ type: "text", text: JSON.stringify(res, null, 2) }]
1074
- };
1075
- });
1076
- defineTool(server, "subscriptions_delete", "Delete a subscription. Pending outbox rows are cascade-deleted.", { id: z8.string() }, async ({ id }) => {
708
+ defineTool(server, "subscriptions_delete", "Delete a subscription. Pending outbox rows are cascade-deleted.", { id: z6.string() }, async ({ id }) => {
1077
709
  const res = await clientProvider().subscriptions.delete(id);
1078
710
  return {
1079
711
  content: [{ type: "text", text: JSON.stringify(res, null, 2) }]
1080
712
  };
1081
713
  });
1082
- defineTool(server, "subscriptions_rotate_secret", "Rotate a subscription signing secret. Returns the new plaintext secret once.", { id: z8.string() }, async ({ id }) => {
1083
- const res = await clientProvider().subscriptions.rotateSecret(id);
1084
- return {
1085
- content: [{ type: "text", text: JSON.stringify(res, null, 2) }]
1086
- };
1087
- });
1088
- 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 — check subscriptions_recent_deliveries. Returns {ok, statusCode, error, durationMs, deliveryId}.", { id: z8.string().describe("Subscription id") }, async ({ id }) => {
714
+ 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: z6.string().describe("Subscription id") }, async ({ id }) => {
1089
715
  const res = await clientProvider().subscriptions.test(id);
1090
716
  return {
1091
717
  content: [{ type: "text", text: JSON.stringify(res, null, 2) }]
1092
718
  };
1093
719
  });
1094
720
  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.", {
1095
- id: z8.string(),
1096
- fromBlock: z8.number().int().nonnegative(),
1097
- toBlock: z8.number().int().nonnegative(),
1098
- force: z8.string().optional().describe("Idempotency suffix to force a duplicate replay of the range")
721
+ id: z6.string(),
722
+ fromBlock: z6.number().int().nonnegative(),
723
+ toBlock: z6.number().int().nonnegative(),
724
+ force: z6.string().optional().describe("Idempotency suffix to force a duplicate replay of the range")
1099
725
  }, async ({ id, fromBlock, toBlock, force }) => {
1100
726
  const res = await clientProvider().subscriptions.replay(id, {
1101
727
  fromBlock,
@@ -1106,27 +732,6 @@ function registerSubscriptionTools(server, clientProvider = getClient) {
1106
732
  content: [{ type: "text", text: JSON.stringify(res, null, 2) }]
1107
733
  };
1108
734
  });
1109
- defineTool(server, "subscriptions_dead", "Return the last 100 dead-letter outbox rows for a subscription.", { id: z8.string() }, async ({ id }) => {
1110
- const { data } = await clientProvider().subscriptions.dead(id);
1111
- return {
1112
- content: [{ type: "text", text: JSON.stringify(data, null, 2) }]
1113
- };
1114
- });
1115
- defineTool(server, "subscriptions_requeue_dead", "Requeue one dead-letter outbox row for delivery retry.", {
1116
- id: z8.string(),
1117
- outboxId: z8.string()
1118
- }, async ({ id, outboxId }) => {
1119
- const res = await clientProvider().subscriptions.requeueDead(id, outboxId);
1120
- return {
1121
- content: [{ type: "text", text: JSON.stringify(res, null, 2) }]
1122
- };
1123
- });
1124
- defineTool(server, "subscriptions_recent_deliveries", "Return the last 100 delivery attempts (attempt #, status code, duration, truncated response).", { id: z8.string() }, async ({ id }) => {
1125
- const { data } = await clientProvider().subscriptions.recentDeliveries(id);
1126
- return {
1127
- content: [{ type: "text", text: JSON.stringify(data, null, 2) }]
1128
- };
1129
- });
1130
735
  }
1131
736
 
1132
737
  // src/server.ts
@@ -1141,7 +746,6 @@ function createServer() {
1141
746
  registerSubgraphTools(server);
1142
747
  registerSubscriptionTools(server);
1143
748
  registerAccountTools(server);
1144
- registerProjectTools(server);
1145
749
  registerIndexTools(server);
1146
750
  registerStreamsTools(server);
1147
751
  registerContractTools(server);
@@ -1154,5 +758,5 @@ var server = createServer();
1154
758
  var transport = new StdioServerTransport;
1155
759
  await server.connect(transport);
1156
760
 
1157
- //# debugId=DF363B254E9A96CE64756E2164756E21
761
+ //# debugId=63BF73C1A0B18EDD64756E2164756E21
1158
762
  //# sourceMappingURL=bin.js.map