@secondlayer/mcp 3.4.0 → 3.6.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/index.js CHANGED
@@ -159,7 +159,8 @@ var PRODUCT_BLURBS = {
159
159
  contracts: "trait-based contract discovery",
160
160
  subgraphs: "author/deploy/query custom indexes",
161
161
  subscriptions: "webhook delivery on subgraph rows or raw chain events",
162
- account: "identity, plan, billing, and API keys",
162
+ account: "identity, plan, billing, usage, spend caps, and API keys",
163
+ project: "create/manage projects and view their team",
163
164
  scaffold: "generate typed contract clients from a deployment or ABI"
164
165
  };
165
166
  var PRODUCT_ORDER = [
@@ -170,6 +171,7 @@ var PRODUCT_ORDER = [
170
171
  "subgraphs",
171
172
  "subscriptions",
172
173
  "account",
174
+ "project",
173
175
  "scaffold"
174
176
  ];
175
177
  function buildCapabilities() {
@@ -212,6 +214,8 @@ async function buildContext(deps = { clientProvider: getClient }) {
212
214
  indexTip: orNull(snap?.indexTip),
213
215
  subgraphs: snap?.subgraphs ? snap.subgraphs.map(formatSubgraphSummary) : unavailable,
214
216
  subscriptions: orNull(snap?.subscriptions),
217
+ projects: orNull(snap?.projects),
218
+ apiKeys: orNull(snap?.apiKeys),
215
219
  activeOperations: orNull(snap?.activeOperations)
216
220
  },
217
221
  whatYouCanDo: buildCapabilities(),
@@ -280,6 +284,23 @@ function registerAccountTools(server) {
280
284
  product: z.enum(["streams", "index"]).optional().describe("Key scope (default streams)"),
281
285
  name: z.string().optional().describe("Optional label for the key")
282
286
  }, async ({ product, name }) => jsonResponse(await getClient().apiKeys.create({ product, name })));
287
+ 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()));
288
+ 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)));
289
+ 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")));
290
+ 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")));
291
+ 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.", {
292
+ monthlyCapCents: z.number().int().nonnegative().optional().describe("Total monthly spend cap in cents"),
293
+ computeCapCents: z.number().int().nonnegative().optional().describe("Compute spend cap in cents"),
294
+ storageCapCents: z.number().int().nonnegative().optional().describe("Storage spend cap in cents"),
295
+ alertThresholdPct: z.number().int().min(1).max(100).optional().describe("Percent of cap that triggers an alert (1-100)")
296
+ }, async (caps) => {
297
+ const body = {};
298
+ for (const [k, v] of Object.entries(caps)) {
299
+ if (v !== undefined)
300
+ body[k] = v;
301
+ }
302
+ return jsonResponse(await apiRequest("PATCH", "/api/billing/caps", body));
303
+ });
283
304
  }
284
305
 
285
306
  // src/tools/contracts.ts
@@ -301,7 +322,7 @@ function registerDatasetTools(server, clientProvider = getClient) {
301
322
  const catalog = await clientProvider().datasets.listDatasets();
302
323
  return jsonResponse(catalog);
303
324
  });
304
- defineTool(server, "datasets_query", 'Query a cursor-paginated Foundation Dataset by slug (e.g. "stx-transfers", "sbtc/events", "pox-4/calls", "bns/events"). Filters are passed through as documented query params (e.g. {"sender": "SP...", "from_block": "150000"}). Returns { rows, next_cursor, tip }. Call datasets_list first to discover slugs.', {
325
+ defineTool(server, "datasets_query", 'Query ANY Foundation Dataset by slug — every family returned by datasets_list is queryable, including bespoke ones (bns/resolve with {"fqn":"alice.btc"}, bns/names, bns/namespaces, network-health/summary) and any dataset added later. Accepts family ("sbtc-events") or path ("sbtc/events") slug forms. Filters are passed through as documented query params (e.g. {"sender": "SP...", "from_block": "150000"}). Returns { rows, next_cursor, tip }; single-record datasets like bns/resolve return 0-or-1 rows (empty = not found). Call datasets_list first to discover slugs and their filters.', {
305
326
  slug: z3.string().describe("Dataset slug from datasets_list (e.g. stx-transfers)"),
306
327
  filters: z3.record(z3.string(), z3.string()).optional().describe("Documented per-dataset query params (snake_case values)"),
307
328
  limit: z3.number().optional().describe("Max rows for this page"),
@@ -312,7 +333,7 @@ function registerDatasetTools(server, clientProvider = getClient) {
312
333
  params.limit = limit;
313
334
  if (cursor !== undefined)
314
335
  params.cursor = cursor;
315
- const result = await clientProvider().datasets.query(slug, params);
336
+ const result = await clientProvider().datasets.get(slug, params);
316
337
  return jsonResponse(result);
317
338
  });
318
339
  }
@@ -408,9 +429,43 @@ function registerIndexTools(server, clientProvider = getClient) {
408
429
  });
409
430
  }
410
431
 
432
+ // src/tools/projects.ts
433
+ import { z as z5 } from "zod/v4";
434
+ function registerProjectTools(server, clientProvider = getClient) {
435
+ defineTool(server, "project_list", "List the account's projects. Requires an account-level (owner) API key.", {}, async () => jsonResponse(await clientProvider().projects.list()));
436
+ defineTool(server, "project_get", "Get a single project by slug.", { slug: z5.string().describe("Project slug") }, async ({ slug }) => jsonResponse(await clientProvider().projects.get(slug)));
437
+ defineTool(server, "project_create", "Create a project. The slug is derived from the name when omitted. Requires an account-level (owner) API key.", {
438
+ name: z5.string().describe("Project name"),
439
+ slug: z5.string().optional().describe("URL slug (auto-derived from name if omitted)"),
440
+ network: z5.string().optional().describe("Network (e.g. mainnet, testnet)"),
441
+ nodeRpc: z5.string().optional().describe("Custom node RPC URL")
442
+ }, async ({ name, slug, network, nodeRpc }) => jsonResponse(await clientProvider().projects.create({
443
+ name,
444
+ slug,
445
+ network,
446
+ nodeRpc
447
+ })));
448
+ defineTool(server, "project_update", "Update a project. `slug` selects the project; `newSlug` renames it. Requires an account-level (owner) API key.", {
449
+ slug: z5.string().describe("Slug of the project to update"),
450
+ newSlug: z5.string().optional().describe("New slug (renames the project)"),
451
+ name: z5.string().optional().describe("New display name"),
452
+ network: z5.string().optional().describe("Network (e.g. mainnet, testnet)"),
453
+ nodeRpc: z5.string().optional().describe("Custom node RPC URL"),
454
+ settings: z5.record(z5.string(), z5.unknown()).optional().describe("Arbitrary project settings to merge")
455
+ }, async ({ slug, newSlug, name, network, nodeRpc, settings }) => jsonResponse(await clientProvider().projects.update(slug, {
456
+ ...newSlug !== undefined ? { slug: newSlug } : {},
457
+ ...name !== undefined ? { name } : {},
458
+ ...network !== undefined ? { network } : {},
459
+ ...nodeRpc !== undefined ? { nodeRpc } : {},
460
+ ...settings !== undefined ? { settings } : {}
461
+ })));
462
+ defineTool(server, "project_delete", "Delete a project permanently. The account's last remaining project cannot be deleted.", { slug: z5.string().describe("Project slug") }, async ({ slug }) => jsonResponse(await clientProvider().projects.delete(slug)));
463
+ defineTool(server, "project_team_list", "List a project's team members and pending invitations.", { slug: z5.string().describe("Project slug") }, async ({ slug }) => jsonResponse(await clientProvider().projects.team(slug)));
464
+ }
465
+
411
466
  // src/tools/scaffold.ts
412
467
  import { generateSubgraphCode } from "@secondlayer/scaffold";
413
- import { z as z5 } from "zod/v4";
468
+ import { z as z6 } from "zod/v4";
414
469
  var API_BASE = process.env.SECONDLAYER_API_URL || "https://api.secondlayer.tools";
415
470
  async function fetchAbi(contractId) {
416
471
  const res = await fetch(`${API_BASE}/api/node/contracts/${contractId}/abi`, {
@@ -429,17 +484,17 @@ async function fetchAbi(contractId) {
429
484
  }
430
485
  function registerScaffoldTools(server) {
431
486
  defineTool(server, "scaffold_from_contract", "Generate a subgraph scaffold from a deployed Stacks contract. Fetches the ABI automatically.", {
432
- contractId: z5.string().describe("Fully qualified contract ID (e.g. SP102V8P0F7JX67ARQ77WEA3D3CFB5XW39REDT0AM.amm-pool-v2-01)"),
433
- subgraphName: z5.string().optional().describe("Override the subgraph name (defaults to contract name)")
487
+ contractId: z6.string().describe("Fully qualified contract ID (e.g. SP102V8P0F7JX67ARQ77WEA3D3CFB5XW39REDT0AM.amm-pool-v2-01)"),
488
+ subgraphName: z6.string().optional().describe("Override the subgraph name (defaults to contract name)")
434
489
  }, async ({ contractId, subgraphName }) => {
435
490
  const { functions, maps } = await fetchAbi(contractId);
436
491
  const code = generateSubgraphCode(contractId, functions, subgraphName, maps);
437
492
  return { content: [{ type: "text", text: code }] };
438
493
  });
439
494
  defineTool(server, "scaffold_from_abi", "Generate a subgraph scaffold from a provided ABI JSON. Use when you already have the ABI.", {
440
- abi: z5.string().describe("ABI JSON string (the full contract ABI object)"),
441
- contractId: z5.string().describe("Fully qualified contract ID"),
442
- subgraphName: z5.string().optional().describe("Override the subgraph name")
495
+ abi: z6.string().describe("ABI JSON string (the full contract ABI object)"),
496
+ contractId: z6.string().describe("Fully qualified contract ID"),
497
+ subgraphName: z6.string().optional().describe("Override the subgraph name")
443
498
  }, async ({ abi, contractId, subgraphName }) => {
444
499
  let parsed;
445
500
  try {
@@ -458,7 +513,7 @@ function registerScaffoldTools(server) {
458
513
  // src/tools/streams.ts
459
514
  import { AuthError } from "@secondlayer/sdk";
460
515
  import { DECODED_EVENT_TYPES as DECODED_EVENT_TYPES2 } from "@secondlayer/shared";
461
- import { z as z6 } from "zod/v4";
516
+ import { z as z7 } from "zod/v4";
462
517
  var STREAMS_EVENT_TYPES = DECODED_EVENT_TYPES2;
463
518
  async function withStreamsAuthHint(fn) {
464
519
  try {
@@ -473,28 +528,28 @@ async function withStreamsAuthHint(fn) {
473
528
  function registerStreamsTools(server, clientProvider = getClient) {
474
529
  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())));
475
530
  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.", {
476
- types: z6.array(z6.enum(STREAMS_EVENT_TYPES)).optional().describe("Event types to include"),
477
- notTypes: z6.array(z6.enum(STREAMS_EVENT_TYPES)).optional().describe("Event types to exclude (applied after types)"),
478
- contractId: z6.string().optional().describe("Filter by contract id"),
479
- sender: z6.string().optional().describe("Filter by sender principal"),
480
- recipient: z6.string().optional().describe("Filter by recipient principal"),
481
- assetIdentifier: z6.string().optional().describe("Filter by asset identifier"),
482
- fromHeight: z6.number().optional().describe("Start block height (inclusive)"),
483
- toHeight: z6.number().optional().describe("End block height (inclusive)"),
484
- cursor: z6.string().optional().describe("Opaque cursor from a prior response"),
485
- limit: z6.number().optional().describe("Max events for this page")
531
+ types: z7.array(z7.enum(STREAMS_EVENT_TYPES)).optional().describe("Event types to include"),
532
+ notTypes: z7.array(z7.enum(STREAMS_EVENT_TYPES)).optional().describe("Event types to exclude (applied after types)"),
533
+ contractId: z7.string().optional().describe("Filter by contract id"),
534
+ sender: z7.string().optional().describe("Filter by sender principal"),
535
+ recipient: z7.string().optional().describe("Filter by recipient principal"),
536
+ assetIdentifier: z7.string().optional().describe("Filter by asset identifier"),
537
+ fromHeight: z7.number().optional().describe("Start block height (inclusive)"),
538
+ toHeight: z7.number().optional().describe("End block height (inclusive)"),
539
+ cursor: z7.string().optional().describe("Opaque cursor from a prior response"),
540
+ limit: z7.number().optional().describe("Max events for this page")
486
541
  }, async (params) => withStreamsAuthHint(async () => jsonResponse(await clientProvider().streams.events.list(params))));
487
542
  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).", {
488
- fromCursor: z6.string().optional().describe("Resume cursor from a prior consume (omit to start at genesis)"),
489
- types: z6.array(z6.enum(STREAMS_EVENT_TYPES)).optional().describe("Event types to include"),
490
- notTypes: z6.array(z6.enum(STREAMS_EVENT_TYPES)).optional().describe("Event types to exclude"),
491
- contractId: z6.string().optional().describe("Filter by contract id"),
492
- sender: z6.string().optional().describe("Filter by sender principal"),
493
- recipient: z6.string().optional().describe("Filter by recipient principal"),
494
- assetIdentifier: z6.string().optional().describe("Filter by asset identifier"),
495
- batchSize: z6.number().optional().describe("Events per page (1–1000, default 100)"),
496
- maxPages: z6.number().optional().describe("Max pages to walk this call (1–20, default 5)"),
497
- finalizedOnly: z6.boolean().optional().describe("Only emit finalized events; skip reorg handling")
543
+ fromCursor: z7.string().optional().describe("Resume cursor from a prior consume (omit to start at genesis)"),
544
+ types: z7.array(z7.enum(STREAMS_EVENT_TYPES)).optional().describe("Event types to include"),
545
+ notTypes: z7.array(z7.enum(STREAMS_EVENT_TYPES)).optional().describe("Event types to exclude"),
546
+ contractId: z7.string().optional().describe("Filter by contract id"),
547
+ sender: z7.string().optional().describe("Filter by sender principal"),
548
+ recipient: z7.string().optional().describe("Filter by recipient principal"),
549
+ assetIdentifier: z7.string().optional().describe("Filter by asset identifier"),
550
+ batchSize: z7.number().optional().describe("Events per page (1–1000, default 100)"),
551
+ maxPages: z7.number().optional().describe("Max pages to walk this call (1–20, default 5)"),
552
+ finalizedOnly: z7.boolean().optional().describe("Only emit finalized events; skip reorg handling")
498
553
  }, async (params) => withStreamsAuthHint(async () => {
499
554
  const maxPages = Math.min(Math.max(params.maxPages ?? 5, 1), 20);
500
555
  const batchSize = Math.min(Math.max(params.batchSize ?? 100, 1), 1000);
@@ -526,26 +581,27 @@ function registerStreamsTools(server, clientProvider = getClient) {
526
581
  pages: result.pages
527
582
  });
528
583
  }));
529
- 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))));
584
+ defineTool(server, "streams_event_by_txid", "List all Streams events emitted by a single transaction. Streams requires an API key (SL_API_KEY).", { txId: z7.string().describe("Transaction id (0x… hash)") }, async ({ txId }) => withStreamsAuthHint(async () => jsonResponse(await clientProvider().streams.events.byTxId(txId))));
530
585
  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).", {
531
- heightOrHash: z6.string().describe("Block height (digits) or block hash (0x… string)")
586
+ heightOrHash: z7.string().describe("Block height (digits) or block hash (0x… string)")
532
587
  }, async ({ heightOrHash }) => withStreamsAuthHint(async () => jsonResponse(await clientProvider().streams.blocks.events(/^\d+$/.test(heightOrHash) ? Number(heightOrHash) : heightOrHash))));
533
588
  defineTool(server, "streams_reorgs", "List chain reorgs observed by Streams since a cursor. Streams requires an API key (SL_API_KEY).", {
534
- since: z6.string().describe("Cursor to list reorgs since (block:index or ISO timestamp)"),
535
- limit: z6.number().optional().describe("Max reorgs to return")
589
+ since: z7.string().describe("Cursor to list reorgs since (block:index or ISO timestamp)"),
590
+ limit: z7.number().optional().describe("Max reorgs to return")
536
591
  }, async (params) => withStreamsAuthHint(async () => jsonResponse(await clientProvider().streams.reorgs.list(params))));
537
- 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))));
592
+ 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: z7.number().describe("Block height") }, async ({ height }) => withStreamsAuthHint(async () => jsonResponse(await clientProvider().streams.canonical(height))));
538
593
  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())));
539
594
  }
540
595
 
541
596
  // src/tools/subgraphs.ts
542
597
  import { bundleSubgraphCode } from "@secondlayer/bundler";
598
+ import { ByoBreakingChangeError } from "@secondlayer/sdk";
543
599
  import {
544
600
  generateDrizzleSchema,
545
601
  generateKyselySchema,
546
602
  generatePrismaSchema
547
603
  } from "@secondlayer/subgraphs";
548
- import { z as z7 } from "zod/v4";
604
+ import { z as z8 } from "zod/v4";
549
605
  function registerSubgraphTools(server, clientProvider = getClient) {
550
606
  defineTool(server, "subgraphs_list", "List all deployed subgraphs. Returns summary fields only.", {}, async () => {
551
607
  const { data } = await clientProvider().subgraphs.list();
@@ -558,16 +614,16 @@ function registerSubgraphTools(server, clientProvider = getClient) {
558
614
  ]
559
615
  };
560
616
  });
561
- defineTool(server, "subgraphs_get", "Get full details of a subgraph including schema, health, and table columns.", { name: z7.string().describe("Subgraph name") }, async ({ name }) => {
617
+ defineTool(server, "subgraphs_get", "Get full details of a subgraph including schema, health, and table columns.", { name: z8.string().describe("Subgraph name") }, async ({ name }) => {
562
618
  const detail = await clientProvider().subgraphs.get(name);
563
619
  return {
564
620
  content: [{ type: "text", text: JSON.stringify(detail, null, 2) }]
565
621
  };
566
622
  });
567
623
  defineTool(server, "subgraphs_spec", "Get generated API documentation for a subgraph. Defaults to compact agent schema; supports OpenAPI JSON and Markdown.", {
568
- name: z7.string().describe("Subgraph name"),
569
- format: z7.enum(["agent", "openapi", "markdown"]).optional().describe("Spec format to return. Defaults to agent."),
570
- serverUrl: z7.string().optional().describe("Override the server URL embedded in generated docs.")
624
+ name: z8.string().describe("Subgraph name"),
625
+ format: z8.enum(["agent", "openapi", "markdown"]).optional().describe("Spec format to return. Defaults to agent."),
626
+ serverUrl: z8.string().optional().describe("Override the server URL embedded in generated docs.")
571
627
  }, async ({ name, format = "agent", serverUrl }) => {
572
628
  const options = serverUrl ? { serverUrl } : undefined;
573
629
  const spec = format === "openapi" ? await clientProvider().subgraphs.openapi(name, options) : format === "markdown" ? await clientProvider().subgraphs.markdown(name, options) : await clientProvider().subgraphs.schema(name, options);
@@ -581,15 +637,15 @@ function registerSubgraphTools(server, clientProvider = getClient) {
581
637
  };
582
638
  });
583
639
  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.', {
584
- name: z7.string().describe("Subgraph name"),
585
- table: z7.string().describe("Table name"),
586
- filters: z7.record(z7.string(), z7.string()).optional().describe('Column filters — plain values or with operators (e.g. {"amount.gte": "1000", "sender": "SP..."})'),
587
- sort: z7.string().optional().describe("Column to sort by"),
588
- order: z7.enum(["asc", "desc"]).optional().describe("Sort order"),
589
- limit: z7.number().max(200).optional().describe("Max rows (default 50, max 200)"),
590
- offset: z7.number().optional().describe("Offset for pagination"),
591
- fields: z7.string().optional().describe('Comma-separated column list to return (e.g. "sender,amount")'),
592
- count: z7.boolean().optional().describe("If true, return row count instead of rows")
640
+ name: z8.string().describe("Subgraph name"),
641
+ table: z8.string().describe("Table name"),
642
+ filters: z8.record(z8.string(), z8.string()).optional().describe('Column filters — plain values or with operators (e.g. {"amount.gte": "1000", "sender": "SP..."})'),
643
+ sort: z8.string().optional().describe("Column to sort by"),
644
+ order: z8.enum(["asc", "desc"]).optional().describe("Sort order"),
645
+ limit: z8.number().max(200).optional().describe("Max rows (default 50, max 200)"),
646
+ offset: z8.number().optional().describe("Offset for pagination"),
647
+ fields: z8.string().optional().describe('Comma-separated column list to return (e.g. "sender,amount")'),
648
+ count: z8.boolean().optional().describe("If true, return row count instead of rows")
593
649
  }, async ({
594
650
  name,
595
651
  table,
@@ -621,10 +677,25 @@ function registerSubgraphTools(server, clientProvider = getClient) {
621
677
  content: [{ type: "text", text: JSON.stringify(result, null, 2) }]
622
678
  };
623
679
  });
680
+ 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.`, {
681
+ name: z8.string().describe("Subgraph name"),
682
+ table: z8.string().describe("Table name"),
683
+ filters: z8.record(z8.string(), z8.string()).optional().describe('Column filters — plain values or with operators (e.g. {"amount.gte": "1000", "sender": "SP..."})'),
684
+ count: z8.boolean().optional().describe("Include COUNT(*) of matching rows"),
685
+ countDistinct: z8.array(z8.string()).optional().describe("Columns to count distinct values of"),
686
+ sum: z8.array(z8.string()).optional().describe("Numeric columns to sum (lossless string result)"),
687
+ min: z8.array(z8.string()).optional().describe("Numeric columns to take the minimum of"),
688
+ max: z8.array(z8.string()).optional().describe("Numeric columns to take the maximum of")
689
+ }, async ({ name, table, filters, count, countDistinct, sum, min, max }) => {
690
+ const result = await clientProvider().subgraphs.queryTableAggregate(name, table, { filters, count, countDistinct, sum, min, max });
691
+ return {
692
+ content: [{ type: "text", text: JSON.stringify(result, null, 2) }]
693
+ };
694
+ });
624
695
  defineTool(server, "subgraphs_reindex", "Reindex a subgraph from a specific block range. Returns an operationId — poll subgraphs_operation to track progress to completion.", {
625
- name: z7.string().describe("Subgraph name"),
626
- fromBlock: z7.number().optional().describe("Start block (defaults to beginning)"),
627
- toBlock: z7.number().optional().describe("End block (defaults to latest)")
696
+ name: z8.string().describe("Subgraph name"),
697
+ fromBlock: z8.number().optional().describe("Start block (defaults to beginning)"),
698
+ toBlock: z8.number().optional().describe("End block (defaults to latest)")
628
699
  }, async ({ name, fromBlock, toBlock }) => {
629
700
  const result = await clientProvider().subgraphs.reindex(name, {
630
701
  fromBlock,
@@ -635,48 +706,100 @@ function registerSubgraphTools(server, clientProvider = getClient) {
635
706
  };
636
707
  });
637
708
  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.", {
638
- name: z7.string().describe("Subgraph name"),
639
- operationId: z7.string().optional().describe("Operation id from reindex/backfill/stop; omit to list recent operations")
709
+ name: z8.string().describe("Subgraph name"),
710
+ operationId: z8.string().optional().describe("Operation id from reindex/backfill/stop; omit to list recent operations")
640
711
  }, async ({ name, operationId }) => {
641
712
  const result = operationId ? await clientProvider().subgraphs.getOperation(name, operationId) : await clientProvider().subgraphs.operations(name);
642
713
  return {
643
714
  content: [{ type: "text", text: JSON.stringify(result, null, 2) }]
644
715
  };
645
716
  });
646
- defineTool(server, "subgraphs_delete", "Delete a subgraph permanently.", { name: z7.string().describe("Subgraph name") }, async ({ name }) => {
647
- const result = await clientProvider().subgraphs.delete(name);
648
- return { content: [{ type: "text", text: result.message }] };
717
+ 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.", {
718
+ name: z8.string().describe("Subgraph name"),
719
+ fromBlock: z8.number().int().nonnegative().describe("Start block (inclusive)"),
720
+ toBlock: z8.number().int().nonnegative().describe("End block (inclusive)")
721
+ }, async ({ name, fromBlock, toBlock }) => {
722
+ const result = await clientProvider().subgraphs.backfill(name, {
723
+ fromBlock,
724
+ toBlock
725
+ });
726
+ return {
727
+ content: [{ type: "text", text: JSON.stringify(result, null, 2) }]
728
+ };
649
729
  });
650
- 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. Call `subgraphs_reindex` separately if you need a forced reindex.", {
651
- code: z7.string().describe("TypeScript source code containing a defineSubgraph() call"),
652
- startBlock: z7.number().int().nonnegative().optional().describe("Override the definition startBlock for this deploy")
653
- }, async ({ code, startBlock }) => {
654
- const bundled = await bundleSubgraphCode(code);
655
- const result = await clientProvider().subgraphs.deploy({
656
- name: bundled.name,
657
- version: bundled.version,
658
- description: bundled.description,
659
- sources: bundled.sources,
660
- schema: bundled.schema,
661
- handlerCode: bundled.handlerCode,
662
- sourceCode: code,
663
- ...startBlock !== undefined ? { startBlock } : {}
730
+ 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: z8.string().describe("Subgraph name") }, async ({ name }) => {
731
+ const result = await clientProvider().subgraphs.stop(name);
732
+ return {
733
+ content: [{ type: "text", text: JSON.stringify(result, null, 2) }]
734
+ };
735
+ });
736
+ 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.", {
737
+ name: z8.string().describe("Subgraph name"),
738
+ limit: z8.number().int().positive().optional().describe("Max gaps to return"),
739
+ offset: z8.number().int().nonnegative().optional().describe("Pagination offset"),
740
+ resolved: z8.boolean().optional().describe("Filter by resolved state (omit for unresolved only)")
741
+ }, async ({ name, limit, offset, resolved }) => {
742
+ const result = await clientProvider().subgraphs.gaps(name, {
743
+ limit,
744
+ offset,
745
+ resolved
664
746
  });
665
747
  return {
666
748
  content: [{ type: "text", text: JSON.stringify(result, null, 2) }]
667
749
  };
668
750
  });
669
- 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 }) => {
751
+ defineTool(server, "subgraphs_delete", "Delete a subgraph permanently.", { name: z8.string().describe("Subgraph name") }, async ({ name }) => {
752
+ const result = await clientProvider().subgraphs.delete(name);
753
+ return { content: [{ type: "text", text: result.message }] };
754
+ });
755
+ 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. Call `subgraphs_reindex` separately if you need a forced reindex.", {
756
+ code: z8.string().describe("TypeScript source code containing a defineSubgraph() call"),
757
+ startBlock: z8.number().int().nonnegative().optional().describe("Override the definition startBlock for this deploy"),
758
+ databaseUrl: z8.string().optional().describe("BYO data plane: Postgres connection string to host the subgraph's schema and rows in your own database"),
759
+ dryRun: z8.boolean().optional().describe("Validate and preview the deploy (schema/DDL, BYO connection) without writing changes")
760
+ }, async ({ code, startBlock, databaseUrl, dryRun }) => {
761
+ const bundled = await bundleSubgraphCode(code);
762
+ try {
763
+ const result = await clientProvider().subgraphs.deploy({
764
+ name: bundled.name,
765
+ version: bundled.version,
766
+ description: bundled.description,
767
+ sources: bundled.sources,
768
+ schema: bundled.schema,
769
+ handlerCode: bundled.handlerCode,
770
+ sourceCode: code,
771
+ ...startBlock !== undefined ? { startBlock } : {},
772
+ ...databaseUrl !== undefined ? { databaseUrl } : {},
773
+ ...dryRun !== undefined ? { dryRun } : {}
774
+ });
775
+ return {
776
+ content: [{ type: "text", text: JSON.stringify(result, null, 2) }]
777
+ };
778
+ } catch (err) {
779
+ if (err instanceof ByoBreakingChangeError) {
780
+ return {
781
+ content: [
782
+ {
783
+ type: "text",
784
+ text: JSON.stringify({ byoBreakingChange: true, ...err.details }, null, 2)
785
+ }
786
+ ]
787
+ };
788
+ }
789
+ throw err;
790
+ }
791
+ });
792
+ 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: z8.string().describe("Subgraph name") }, async ({ name }) => {
670
793
  const source = await clientProvider().subgraphs.getSource(name);
671
794
  return {
672
795
  content: [{ type: "text", text: JSON.stringify(source, null, 2) }]
673
796
  };
674
797
  });
675
798
  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.", {
676
- code: z7.string().optional().describe("defineSubgraph() source (mutually exclusive with name)"),
677
- name: z7.string().optional().describe("Deployed subgraph name (mutually exclusive with code)"),
678
- target: z7.enum(["prisma", "drizzle", "kysely"]).optional().describe("ORM target (default prisma)"),
679
- schemaName: z7.string().optional().describe("Postgres schema name (defaults to subgraph_<name>)")
799
+ code: z8.string().optional().describe("defineSubgraph() source (mutually exclusive with name)"),
800
+ name: z8.string().optional().describe("Deployed subgraph name (mutually exclusive with code)"),
801
+ target: z8.enum(["prisma", "drizzle", "kysely"]).optional().describe("ORM target (default prisma)"),
802
+ schemaName: z8.string().optional().describe("Postgres schema name (defaults to subgraph_<name>)")
680
803
  }, async ({ code, name, target = "prisma", schemaName }) => {
681
804
  if (code && name || !code && !name) {
682
805
  throw new Error("Provide exactly one of `code` or `name`.");
@@ -705,7 +828,7 @@ function registerSubgraphTools(server, clientProvider = getClient) {
705
828
 
706
829
  // src/tools/subscriptions.ts
707
830
  import { CHAIN_TRIGGER_TYPES } from "@secondlayer/shared";
708
- import { z as z8 } from "zod/v4";
831
+ import { z as z9 } from "zod/v4";
709
832
  function registerSubscriptionTools(server, clientProvider = getClient) {
710
833
  defineTool(server, "subscriptions_list", "List all subscriptions for the current account. Returns summary fields (no secrets).", {}, async () => {
711
834
  const { data } = await clientProvider().subscriptions.list();
@@ -713,34 +836,34 @@ function registerSubscriptionTools(server, clientProvider = getClient) {
713
836
  content: [{ type: "text", text: JSON.stringify(data, null, 2) }]
714
837
  };
715
838
  });
716
- defineTool(server, "subscriptions_get", "Get full detail for a subscription (filter, auth, retry config, circuit state).", { id: z8.string().describe("Subscription id") }, async ({ id }) => {
839
+ defineTool(server, "subscriptions_get", "Get full detail for a subscription (filter, auth, retry config, circuit state).", { id: z9.string().describe("Subscription id") }, async ({ id }) => {
717
840
  const detail = await clientProvider().subscriptions.get(id);
718
841
  return {
719
842
  content: [{ type: "text", text: JSON.stringify(detail, null, 2) }]
720
843
  };
721
844
  });
722
845
  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.", {
723
- name: z8.string().describe("Human-readable name, unique per account"),
724
- subgraphName: z8.string().optional().describe("Subgraph to subscribe to (subgraph subscription)"),
725
- tableName: z8.string().optional().describe("Table within the subgraph (subgraph subscription)"),
726
- triggers: z8.array(z8.object({
727
- type: z8.enum(CHAIN_TRIGGER_TYPES),
728
- contractId: z8.string().optional(),
729
- functionName: z8.string().optional(),
730
- caller: z8.string().optional(),
731
- sender: z8.string().optional(),
732
- recipient: z8.string().optional(),
733
- assetIdentifier: z8.string().optional(),
734
- deployer: z8.string().optional(),
735
- contractName: z8.string().optional(),
736
- topic: z8.string().optional(),
737
- lockedAddress: z8.string().optional(),
738
- trait: z8.string().optional(),
739
- minAmount: z8.union([z8.string(), z8.number()]).optional(),
740
- maxAmount: z8.union([z8.string(), z8.number()]).optional()
846
+ name: z9.string().describe("Human-readable name, unique per account"),
847
+ subgraphName: z9.string().optional().describe("Subgraph to subscribe to (subgraph subscription)"),
848
+ tableName: z9.string().optional().describe("Table within the subgraph (subgraph subscription)"),
849
+ triggers: z9.array(z9.object({
850
+ type: z9.enum(CHAIN_TRIGGER_TYPES),
851
+ contractId: z9.string().optional(),
852
+ functionName: z9.string().optional(),
853
+ caller: z9.string().optional(),
854
+ sender: z9.string().optional(),
855
+ recipient: z9.string().optional(),
856
+ assetIdentifier: z9.string().optional(),
857
+ deployer: z9.string().optional(),
858
+ contractName: z9.string().optional(),
859
+ topic: z9.string().optional(),
860
+ lockedAddress: z9.string().optional(),
861
+ trait: z9.string().optional(),
862
+ minAmount: z9.union([z9.string(), z9.number()]).optional(),
863
+ maxAmount: z9.union([z9.string(), z9.number()]).optional()
741
864
  })).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. Forward-looking: starts at chain tip, no backfill."),
742
- url: z8.string().describe("Webhook URL"),
743
- format: z8.enum([
865
+ url: z9.string().describe("Webhook URL"),
866
+ format: z9.enum([
744
867
  "standard-webhooks",
745
868
  "inngest",
746
869
  "trigger",
@@ -748,8 +871,8 @@ function registerSubscriptionTools(server, clientProvider = getClient) {
748
871
  "cloudevents",
749
872
  "raw"
750
873
  ]).optional().describe("Wire format (default standard-webhooks)"),
751
- runtime: z8.enum(["inngest", "trigger", "cloudflare", "node"]).optional().describe("Receiver runtime label (display only)"),
752
- filter: z8.record(z8.string(), z8.unknown()).optional().describe('Scalar filter DSL, e.g. {"amount": {"gte": 100}, "sender": "SP..."}')
874
+ runtime: z9.enum(["inngest", "trigger", "cloudflare", "node"]).optional().describe("Receiver runtime label (display only)"),
875
+ filter: z9.record(z9.string(), z9.unknown()).optional().describe('Scalar filter DSL, e.g. {"amount": {"gte": 100}, "sender": "SP..."}')
753
876
  }, async (input) => {
754
877
  const res = await clientProvider().subscriptions.create(input);
755
878
  return {
@@ -757,10 +880,10 @@ function registerSubscriptionTools(server, clientProvider = getClient) {
757
880
  };
758
881
  });
759
882
  defineTool(server, "subscriptions_update", "Patch a subscription (url, filter, format, runtime, retry, timeout, concurrency).", {
760
- id: z8.string(),
761
- url: z8.string().optional(),
762
- filter: z8.record(z8.string(), z8.unknown()).optional(),
763
- format: z8.enum([
883
+ id: z9.string(),
884
+ url: z9.string().optional(),
885
+ filter: z9.record(z9.string(), z9.unknown()).optional(),
886
+ format: z9.enum([
764
887
  "standard-webhooks",
765
888
  "inngest",
766
889
  "trigger",
@@ -768,50 +891,50 @@ function registerSubscriptionTools(server, clientProvider = getClient) {
768
891
  "cloudevents",
769
892
  "raw"
770
893
  ]).optional(),
771
- runtime: z8.enum(["inngest", "trigger", "cloudflare", "node"]).nullable().optional(),
772
- maxRetries: z8.number().int().min(0).optional(),
773
- timeoutMs: z8.number().int().min(100).optional(),
774
- concurrency: z8.number().int().min(1).optional()
894
+ runtime: z9.enum(["inngest", "trigger", "cloudflare", "node"]).nullable().optional(),
895
+ maxRetries: z9.number().int().min(0).optional(),
896
+ timeoutMs: z9.number().int().min(100).optional(),
897
+ concurrency: z9.number().int().min(1).optional()
775
898
  }, async ({ id, ...patch }) => {
776
899
  const res = await clientProvider().subscriptions.update(id, patch);
777
900
  return {
778
901
  content: [{ type: "text", text: JSON.stringify(res, null, 2) }]
779
902
  };
780
903
  });
781
- defineTool(server, "subscriptions_pause", "Pause a subscription. Pending rows remain queued until resumed.", { id: z8.string() }, async ({ id }) => {
904
+ defineTool(server, "subscriptions_pause", "Pause a subscription. Pending rows remain queued until resumed.", { id: z9.string() }, async ({ id }) => {
782
905
  const res = await clientProvider().subscriptions.pause(id);
783
906
  return {
784
907
  content: [{ type: "text", text: JSON.stringify(res, null, 2) }]
785
908
  };
786
909
  });
787
- defineTool(server, "subscriptions_resume", "Resume a paused or circuit-open subscription and reset circuit failures.", { id: z8.string() }, async ({ id }) => {
910
+ defineTool(server, "subscriptions_resume", "Resume a paused or circuit-open subscription and reset circuit failures.", { id: z9.string() }, async ({ id }) => {
788
911
  const res = await clientProvider().subscriptions.resume(id);
789
912
  return {
790
913
  content: [{ type: "text", text: JSON.stringify(res, null, 2) }]
791
914
  };
792
915
  });
793
- defineTool(server, "subscriptions_delete", "Delete a subscription. Pending outbox rows are cascade-deleted.", { id: z8.string() }, async ({ id }) => {
916
+ defineTool(server, "subscriptions_delete", "Delete a subscription. Pending outbox rows are cascade-deleted.", { id: z9.string() }, async ({ id }) => {
794
917
  const res = await clientProvider().subscriptions.delete(id);
795
918
  return {
796
919
  content: [{ type: "text", text: JSON.stringify(res, null, 2) }]
797
920
  };
798
921
  });
799
- defineTool(server, "subscriptions_rotate_secret", "Rotate a subscription signing secret. Returns the new plaintext secret once.", { id: z8.string() }, async ({ id }) => {
922
+ defineTool(server, "subscriptions_rotate_secret", "Rotate a subscription signing secret. Returns the new plaintext secret once.", { id: z9.string() }, async ({ id }) => {
800
923
  const res = await clientProvider().subscriptions.rotateSecret(id);
801
924
  return {
802
925
  content: [{ type: "text", text: JSON.stringify(res, null, 2) }]
803
926
  };
804
927
  });
805
- 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 }) => {
928
+ 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: z9.string().describe("Subscription id") }, async ({ id }) => {
806
929
  const res = await clientProvider().subscriptions.test(id);
807
930
  return {
808
931
  content: [{ type: "text", text: JSON.stringify(res, null, 2) }]
809
932
  };
810
933
  });
811
934
  defineTool(server, "subscriptions_replay", "Replay a block range for a subscription. Replays run at 10% of batch capacity — use sparingly.", {
812
- id: z8.string(),
813
- fromBlock: z8.number().int().nonnegative(),
814
- toBlock: z8.number().int().nonnegative()
935
+ id: z9.string(),
936
+ fromBlock: z9.number().int().nonnegative(),
937
+ toBlock: z9.number().int().nonnegative()
815
938
  }, async ({ id, fromBlock, toBlock }) => {
816
939
  const res = await clientProvider().subscriptions.replay(id, {
817
940
  fromBlock,
@@ -821,22 +944,22 @@ function registerSubscriptionTools(server, clientProvider = getClient) {
821
944
  content: [{ type: "text", text: JSON.stringify(res, null, 2) }]
822
945
  };
823
946
  });
824
- defineTool(server, "subscriptions_dead", "Return the last 100 dead-letter outbox rows for a subscription.", { id: z8.string() }, async ({ id }) => {
947
+ defineTool(server, "subscriptions_dead", "Return the last 100 dead-letter outbox rows for a subscription.", { id: z9.string() }, async ({ id }) => {
825
948
  const { data } = await clientProvider().subscriptions.dead(id);
826
949
  return {
827
950
  content: [{ type: "text", text: JSON.stringify(data, null, 2) }]
828
951
  };
829
952
  });
830
953
  defineTool(server, "subscriptions_requeue_dead", "Requeue one dead-letter outbox row for delivery retry.", {
831
- id: z8.string(),
832
- outboxId: z8.string()
954
+ id: z9.string(),
955
+ outboxId: z9.string()
833
956
  }, async ({ id, outboxId }) => {
834
957
  const res = await clientProvider().subscriptions.requeueDead(id, outboxId);
835
958
  return {
836
959
  content: [{ type: "text", text: JSON.stringify(res, null, 2) }]
837
960
  };
838
961
  });
839
- defineTool(server, "subscriptions_recent_deliveries", "Return the last 100 delivery attempts (attempt #, status code, duration, truncated response).", { id: z8.string() }, async ({ id }) => {
962
+ defineTool(server, "subscriptions_recent_deliveries", "Return the last 100 delivery attempts (attempt #, status code, duration, truncated response).", { id: z9.string() }, async ({ id }) => {
840
963
  const { data } = await clientProvider().subscriptions.recentDeliveries(id);
841
964
  return {
842
965
  content: [{ type: "text", text: JSON.stringify(data, null, 2) }]
@@ -856,6 +979,7 @@ function createServer() {
856
979
  registerSubgraphTools(server);
857
980
  registerSubscriptionTools(server);
858
981
  registerAccountTools(server);
982
+ registerProjectTools(server);
859
983
  registerDatasetTools(server);
860
984
  registerIndexTools(server);
861
985
  registerStreamsTools(server);
@@ -867,5 +991,5 @@ export {
867
991
  createServer
868
992
  };
869
993
 
870
- //# debugId=F809CEC718C9FE6564756E2164756E21
994
+ //# debugId=ADEBB38A46A46AF464756E2164756E21
871
995
  //# sourceMappingURL=index.js.map