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