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