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