@secondlayer/mcp 0.4.1 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -5,10 +5,94 @@ import { fileURLToPath } from "node:url";
5
5
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
6
6
 
7
7
  // src/resources.ts
8
- import { templates } from "@secondlayer/subgraphs/templates";
9
-
10
- // src/tools/streams.ts
11
- import { z } from "zod/v4";
8
+ import { templates as subgraphTemplates } from "@secondlayer/subgraphs/templates";
9
+ import { templates as workflowTemplates } from "@secondlayer/workflows/templates";
10
+ var FILTERS_REFERENCE = [
11
+ { type: "stx_transfer", fields: ["sender", "recipient", "minAmount", "maxAmount"] },
12
+ { type: "stx_mint", fields: ["recipient", "minAmount"] },
13
+ { type: "stx_burn", fields: ["sender", "minAmount"] },
14
+ { type: "stx_lock", fields: ["lockedAddress", "minAmount"] },
15
+ { type: "ft_transfer", fields: ["sender", "recipient", "assetIdentifier", "minAmount", "maxAmount"] },
16
+ { type: "ft_mint", fields: ["recipient", "assetIdentifier", "minAmount"] },
17
+ { type: "ft_burn", fields: ["sender", "assetIdentifier", "minAmount"] },
18
+ { type: "nft_transfer", fields: ["sender", "recipient", "assetIdentifier", "tokenId"] },
19
+ { type: "nft_mint", fields: ["recipient", "assetIdentifier", "tokenId"] },
20
+ { type: "nft_burn", fields: ["sender", "assetIdentifier", "tokenId"] },
21
+ { type: "contract_call", fields: ["contract", "function"] },
22
+ { type: "contract_deploy", fields: ["contract"] },
23
+ { type: "print_event", fields: ["contract", "event", "contains"] }
24
+ ];
25
+ var COLUMN_TYPES = [
26
+ {
27
+ type: "uint",
28
+ sqlType: "bigint",
29
+ description: "Unsigned integer (Clarity uint)"
30
+ },
31
+ {
32
+ type: "int",
33
+ sqlType: "bigint",
34
+ description: "Signed integer (Clarity int)"
35
+ },
36
+ { type: "text", sqlType: "text", description: "UTF-8 string" },
37
+ {
38
+ type: "principal",
39
+ sqlType: "text",
40
+ description: "Stacks address (standard or contract)"
41
+ },
42
+ { type: "bool", sqlType: "boolean", description: "Boolean value" },
43
+ { type: "json", sqlType: "jsonb", description: "Arbitrary JSON data" },
44
+ {
45
+ options: ["nullable", "indexed", "search"],
46
+ description: "Column options: nullable allows NULL, indexed creates a B-tree index, search enables full-text search"
47
+ }
48
+ ];
49
+ function registerResources(server) {
50
+ server.resource("filters", "secondlayer://filters", { description: "Event filter types and their available fields" }, async () => ({
51
+ contents: [
52
+ {
53
+ uri: "secondlayer://filters",
54
+ mimeType: "application/json",
55
+ text: JSON.stringify(FILTERS_REFERENCE, null, 2)
56
+ }
57
+ ]
58
+ }));
59
+ server.resource("column-types", "secondlayer://column-types", { description: "Subgraph column types, SQL mappings, and options" }, async () => ({
60
+ contents: [
61
+ {
62
+ uri: "secondlayer://column-types",
63
+ mimeType: "application/json",
64
+ text: JSON.stringify(COLUMN_TYPES, null, 2)
65
+ }
66
+ ]
67
+ }));
68
+ server.resource("templates", "secondlayer://templates", {
69
+ description: "Available subgraph and workflow templates with descriptions and categories"
70
+ }, async () => ({
71
+ contents: [
72
+ {
73
+ uri: "secondlayer://templates",
74
+ mimeType: "application/json",
75
+ text: JSON.stringify([
76
+ ...subgraphTemplates.map(({ id, name, description, category }) => ({
77
+ kind: "subgraph",
78
+ id,
79
+ name,
80
+ description,
81
+ category
82
+ })),
83
+ ...workflowTemplates.map(({ id, name, description, category, trigger }) => ({
84
+ kind: "workflow",
85
+ id,
86
+ name,
87
+ description,
88
+ category,
89
+ trigger
90
+ }))
91
+ ], null, 2)
92
+ }
93
+ ]
94
+ }));
95
+ }
12
96
 
13
97
  // src/lib/client.ts
14
98
  import { SecondLayer } from "@secondlayer/sdk";
@@ -19,7 +103,12 @@ function getClient() {
19
103
  if (!apiKey) {
20
104
  throw new Error("SECONDLAYER_API_KEY environment variable is required. " + "Get your key at https://app.secondlayer.tools/settings/api-keys");
21
105
  }
22
- instance = new SecondLayer({ apiKey });
106
+ const baseUrl = process.env.SECONDLAYER_API_URL;
107
+ instance = new SecondLayer({
108
+ apiKey,
109
+ origin: "mcp",
110
+ ...baseUrl ? { baseUrl } : {}
111
+ });
23
112
  }
24
113
  return instance;
25
114
  }
@@ -48,16 +137,6 @@ async function apiRequest(method, path, body) {
48
137
  }
49
138
 
50
139
  // src/lib/format.ts
51
- function formatStreamSummary(s) {
52
- return {
53
- id: s.id,
54
- name: s.name,
55
- status: s.status,
56
- endpointUrl: s.endpointUrl,
57
- totalDeliveries: s.totalDeliveries,
58
- failedDeliveries: s.failedDeliveries
59
- };
60
- }
61
140
  function formatSubgraphSummary(s) {
62
141
  return {
63
142
  name: s.name,
@@ -66,16 +145,6 @@ function formatSubgraphSummary(s) {
66
145
  lastProcessedBlock: s.lastProcessedBlock
67
146
  };
68
147
  }
69
- function formatDeliverySummary(d) {
70
- return {
71
- id: d.id,
72
- blockHeight: d.blockHeight,
73
- status: d.status,
74
- statusCode: d.statusCode,
75
- attempts: d.attempts,
76
- createdAt: d.createdAt
77
- };
78
- }
79
148
  function withCap(items, cap) {
80
149
  return {
81
150
  items: items.slice(0, cap),
@@ -83,6 +152,12 @@ function withCap(items, cap) {
83
152
  total: items.length
84
153
  };
85
154
  }
155
+ function jsonResponse(data, isError) {
156
+ return {
157
+ content: [{ type: "text", text: JSON.stringify(data, null, 2) }],
158
+ ...isError && { isError: true }
159
+ };
160
+ }
86
161
 
87
162
  // src/lib/tool.ts
88
163
  function defineTool(server, name, description, schema, handler) {
@@ -107,514 +182,17 @@ function defineTool(server, name, description, schema, handler) {
107
182
  server.tool(name, description, schema, wrappedHandler);
108
183
  }
109
184
 
110
- // src/tools/streams.ts
111
- var FilterSchema = z.discriminatedUnion("type", [
112
- z.object({
113
- type: z.literal("stx_transfer"),
114
- sender: z.string().optional(),
115
- recipient: z.string().optional(),
116
- minAmount: z.number().optional(),
117
- maxAmount: z.number().optional()
118
- }),
119
- z.object({
120
- type: z.literal("stx_mint"),
121
- recipient: z.string().optional(),
122
- minAmount: z.number().optional()
123
- }),
124
- z.object({
125
- type: z.literal("stx_burn"),
126
- sender: z.string().optional(),
127
- minAmount: z.number().optional()
128
- }),
129
- z.object({
130
- type: z.literal("stx_lock"),
131
- lockedAddress: z.string().optional(),
132
- minAmount: z.number().optional()
133
- }),
134
- z.object({
135
- type: z.literal("ft_transfer"),
136
- sender: z.string().optional(),
137
- recipient: z.string().optional(),
138
- assetIdentifier: z.string().optional(),
139
- minAmount: z.number().optional()
140
- }),
141
- z.object({
142
- type: z.literal("ft_mint"),
143
- recipient: z.string().optional(),
144
- assetIdentifier: z.string().optional(),
145
- minAmount: z.number().optional()
146
- }),
147
- z.object({
148
- type: z.literal("ft_burn"),
149
- sender: z.string().optional(),
150
- assetIdentifier: z.string().optional(),
151
- minAmount: z.number().optional()
152
- }),
153
- z.object({
154
- type: z.literal("nft_transfer"),
155
- sender: z.string().optional(),
156
- recipient: z.string().optional(),
157
- assetIdentifier: z.string().optional(),
158
- tokenId: z.string().optional()
159
- }),
160
- z.object({
161
- type: z.literal("nft_mint"),
162
- recipient: z.string().optional(),
163
- assetIdentifier: z.string().optional(),
164
- tokenId: z.string().optional()
165
- }),
166
- z.object({
167
- type: z.literal("nft_burn"),
168
- sender: z.string().optional(),
169
- assetIdentifier: z.string().optional(),
170
- tokenId: z.string().optional()
171
- }),
172
- z.object({
173
- type: z.literal("contract_call"),
174
- contractId: z.string().optional(),
175
- functionName: z.string().optional(),
176
- caller: z.string().optional()
177
- }),
178
- z.object({
179
- type: z.literal("contract_deploy"),
180
- deployer: z.string().optional(),
181
- contractName: z.string().optional()
182
- }),
183
- z.object({
184
- type: z.literal("print_event"),
185
- contractId: z.string().optional(),
186
- topic: z.string().optional(),
187
- contains: z.string().optional()
188
- })
189
- ]);
190
- function registerStreamTools(server) {
191
- defineTool(server, "streams_list", "List all webhook streams. Returns summary fields only.", {
192
- status: z.enum(["active", "inactive", "paused", "failed"]).optional().describe("Filter by status")
193
- }, async ({ status }) => {
194
- const { streams } = await getClient().streams.list(status ? { status } : undefined);
195
- return {
196
- content: [
197
- {
198
- type: "text",
199
- text: JSON.stringify(streams.map(formatStreamSummary), null, 2)
200
- }
201
- ]
202
- };
203
- });
204
- defineTool(server, "streams_get", "Get full details of a stream by ID (accepts UUID prefix).", { id: z.string().describe("Stream UUID or prefix") }, async ({ id }) => {
205
- const stream = await getClient().streams.get(id);
206
- return {
207
- content: [{ type: "text", text: JSON.stringify(stream, null, 2) }]
208
- };
209
- });
210
- defineTool(server, "streams_create", "Create a new webhook stream with filters.", {
211
- name: z.string().describe("Stream name"),
212
- endpointUrl: z.string().describe("Webhook endpoint URL"),
213
- filters: z.array(FilterSchema).min(1).describe("Event filters (at least one required)")
214
- }, async ({ name, endpointUrl, filters }) => {
215
- const result = await getClient().streams.create({
216
- name,
217
- endpointUrl,
218
- filters
219
- });
220
- return {
221
- content: [
222
- {
223
- type: "text",
224
- text: JSON.stringify({ id: result.stream.id, signingSecret: result.signingSecret }, null, 2)
225
- }
226
- ]
227
- };
228
- });
229
- defineTool(server, "streams_update", "Update a stream's name, endpoint, or filters.", {
230
- id: z.string().describe("Stream UUID or prefix"),
231
- name: z.string().optional().describe("New name"),
232
- endpointUrl: z.string().optional().describe("New endpoint URL"),
233
- filters: z.array(FilterSchema).min(1).optional().describe("New filters")
234
- }, async ({ id, name, endpointUrl, filters }) => {
235
- const data = {};
236
- if (name !== undefined)
237
- data.name = name;
238
- if (endpointUrl !== undefined)
239
- data.endpointUrl = endpointUrl;
240
- if (filters !== undefined)
241
- data.filters = filters;
242
- const stream = await getClient().streams.update(id, data);
243
- return {
244
- content: [
245
- {
246
- type: "text",
247
- text: JSON.stringify(formatStreamSummary(stream), null, 2)
248
- }
249
- ]
250
- };
251
- });
252
- defineTool(server, "streams_delete", "Delete a stream permanently.", { id: z.string().describe("Stream UUID or prefix") }, async ({ id }) => {
253
- await getClient().streams.delete(id);
254
- return { content: [{ type: "text", text: `Stream ${id} deleted.` }] };
255
- });
256
- defineTool(server, "streams_toggle", "Enable or disable a stream.", {
257
- id: z.string().describe("Stream UUID or prefix"),
258
- enabled: z.boolean().describe("true to enable, false to disable")
259
- }, async ({ id, enabled }) => {
260
- const stream = enabled ? await getClient().streams.enable(id) : await getClient().streams.disable(id);
261
- return {
262
- content: [
263
- {
264
- type: "text",
265
- text: JSON.stringify({ id: stream.id, status: stream.status }, null, 2)
266
- }
267
- ]
268
- };
269
- });
270
- defineTool(server, "streams_deliveries", "List recent deliveries for a stream (max 25).", {
271
- id: z.string().describe("Stream UUID or prefix"),
272
- limit: z.number().max(25).optional().describe("Max results (default 25)"),
273
- status: z.string().optional().describe("Filter by delivery status")
274
- }, async ({ id, limit, status }) => {
275
- const { deliveries } = await getClient().streams.listDeliveries(id, {
276
- limit: limit ?? 25,
277
- status
278
- });
279
- const result = withCap(deliveries.map(formatDeliverySummary), 25);
280
- return {
281
- content: [{ type: "text", text: JSON.stringify(result, null, 2) }]
282
- };
283
- });
284
- defineTool(server, "streams_pause_all", "Pause all active streams. Without confirm: true, returns a preview of streams that would be paused.", {
285
- confirm: z.boolean().optional().describe("Set to true to execute. Omit or false for preview only.")
286
- }, async ({ confirm }) => {
287
- if (!confirm) {
288
- const { streams } = await getClient().streams.list({
289
- status: "active"
290
- });
291
- const names = streams.map((s) => s.name);
292
- return {
293
- content: [
294
- {
295
- type: "text",
296
- text: JSON.stringify({ preview: true, count: names.length, streams: names }, null, 2)
297
- }
298
- ]
299
- };
300
- }
301
- const result = await getClient().streams.pauseAll();
302
- return {
303
- content: [
304
- {
305
- type: "text",
306
- text: JSON.stringify({
307
- paused: result.paused,
308
- streams: result.streams.map(formatStreamSummary)
309
- }, null, 2)
310
- }
311
- ]
312
- };
313
- });
314
- defineTool(server, "streams_resume_all", "Resume all paused streams. Without confirm: true, returns a preview of streams that would be resumed.", {
315
- confirm: z.boolean().optional().describe("Set to true to execute. Omit or false for preview only.")
316
- }, async ({ confirm }) => {
317
- if (!confirm) {
318
- const { streams } = await getClient().streams.list({
319
- status: "paused"
320
- });
321
- const names = streams.map((s) => s.name);
322
- return {
323
- content: [
324
- {
325
- type: "text",
326
- text: JSON.stringify({ preview: true, count: names.length, streams: names }, null, 2)
327
- }
328
- ]
329
- };
330
- }
331
- const result = await getClient().streams.resumeAll();
332
- return {
333
- content: [
334
- {
335
- type: "text",
336
- text: JSON.stringify({
337
- resumed: result.resumed,
338
- streams: result.streams.map(formatStreamSummary)
339
- }, null, 2)
340
- }
341
- ]
342
- };
343
- });
344
- defineTool(server, "streams_replay", "Replay blocks through a stream, re-delivering events for a block range.", {
345
- id: z.string().describe("Stream UUID or prefix"),
346
- fromBlock: z.number().describe("Start block height (inclusive)"),
347
- toBlock: z.number().describe("End block height (inclusive)")
348
- }, async ({ id, fromBlock, toBlock }) => {
349
- const result = await apiRequest("POST", `/api/streams/${id}/replay`, { fromBlock, toBlock });
350
- return {
351
- content: [{ type: "text", text: JSON.stringify(result, null, 2) }]
352
- };
353
- });
354
- defineTool(server, "streams_rotate_secret", "Rotate the signing secret for a stream. Returns the new secret.", { id: z.string().describe("Stream UUID or prefix") }, async ({ id }) => {
355
- const result = await getClient().streams.rotateSecret(id);
356
- return {
357
- content: [{ type: "text", text: JSON.stringify(result, null, 2) }]
358
- };
359
- });
360
- }
361
-
362
- // src/resources.ts
363
- var FILTERS_REFERENCE = FilterSchema.options.map((opt) => ({
364
- type: opt.shape.type.def.values[0],
365
- fields: Object.keys(opt.shape).filter((k) => k !== "type")
366
- }));
367
- var COLUMN_TYPES = [
368
- {
369
- type: "uint",
370
- sqlType: "bigint",
371
- description: "Unsigned integer (Clarity uint)"
372
- },
373
- {
374
- type: "int",
375
- sqlType: "bigint",
376
- description: "Signed integer (Clarity int)"
377
- },
378
- { type: "text", sqlType: "text", description: "UTF-8 string" },
379
- {
380
- type: "principal",
381
- sqlType: "text",
382
- description: "Stacks address (standard or contract)"
383
- },
384
- { type: "bool", sqlType: "boolean", description: "Boolean value" },
385
- { type: "json", sqlType: "jsonb", description: "Arbitrary JSON data" },
386
- {
387
- options: ["nullable", "indexed", "search"],
388
- description: "Column options: nullable allows NULL, indexed creates a B-tree index, search enables full-text search"
389
- }
390
- ];
391
- function registerResources(server) {
392
- server.resource("filters", "secondlayer://filters", { description: "Stream filter types and their available fields" }, async () => ({
393
- contents: [
394
- {
395
- uri: "secondlayer://filters",
396
- mimeType: "application/json",
397
- text: JSON.stringify(FILTERS_REFERENCE, null, 2)
398
- }
399
- ]
400
- }));
401
- server.resource("column-types", "secondlayer://column-types", { description: "Subgraph column types, SQL mappings, and options" }, async () => ({
402
- contents: [
403
- {
404
- uri: "secondlayer://column-types",
405
- mimeType: "application/json",
406
- text: JSON.stringify(COLUMN_TYPES, null, 2)
407
- }
408
- ]
409
- }));
410
- server.resource("templates", "secondlayer://templates", {
411
- description: "Available subgraph templates with descriptions and categories"
412
- }, async () => ({
413
- contents: [
414
- {
415
- uri: "secondlayer://templates",
416
- mimeType: "application/json",
417
- text: JSON.stringify(templates.map(({ id, name, description, category }) => ({
418
- id,
419
- name,
420
- description,
421
- category
422
- })), null, 2)
423
- }
424
- ]
425
- }));
426
- }
427
-
428
185
  // src/tools/account.ts
429
186
  function registerAccountTools(server) {
430
187
  defineTool(server, "account_whoami", "Show the authenticated account's email and plan.", {}, async () => {
431
188
  const result = await apiRequest("GET", "/api/accounts/me");
432
- return {
433
- content: [{ type: "text", text: JSON.stringify(result, null, 2) }]
434
- };
189
+ return jsonResponse(result);
435
190
  });
436
191
  }
437
192
 
438
193
  // src/tools/scaffold.ts
439
- import { z as z2 } from "zod/v4";
440
-
441
- // src/lib/scaffold-generate.ts
442
- function isAbiBuffer(t) {
443
- return typeof t === "object" && t !== null && "buff" in t;
444
- }
445
- function isAbiStringAscii(t) {
446
- return typeof t === "object" && t !== null && "string-ascii" in t;
447
- }
448
- function isAbiStringUtf8(t) {
449
- return typeof t === "object" && t !== null && "string-utf8" in t;
450
- }
451
- function isAbiOptional(t) {
452
- return typeof t === "object" && t !== null && "optional" in t;
453
- }
454
- function isAbiTuple(t) {
455
- return typeof t === "object" && t !== null && "tuple" in t;
456
- }
457
- function isAbiList(t) {
458
- return typeof t === "object" && t !== null && "list" in t;
459
- }
460
- function isAbiResponse(t) {
461
- return typeof t === "object" && t !== null && "response" in t;
462
- }
463
- function mapType(abiType, nullable) {
464
- if (typeof abiType === "string") {
465
- switch (abiType) {
466
- case "uint128":
467
- return { type: "uint", nullable };
468
- case "int128":
469
- return { type: "int", nullable };
470
- case "principal":
471
- case "trait_reference":
472
- return { type: "principal", nullable };
473
- case "bool":
474
- return { type: "boolean", nullable };
475
- default: {
476
- const s = abiType;
477
- if (s.includes("uint"))
478
- return { type: "uint", nullable };
479
- if (s.includes("int"))
480
- return { type: "int", nullable };
481
- if (s.includes("string") || s.includes("ascii") || s.includes("utf8")) {
482
- return { type: "text", nullable };
483
- }
484
- if (s.includes("buff"))
485
- return { type: "text", nullable };
486
- return { type: "jsonb", nullable };
487
- }
488
- }
489
- }
490
- if (isAbiBuffer(abiType))
491
- return { type: "text", nullable };
492
- if (isAbiStringAscii(abiType) || isAbiStringUtf8(abiType)) {
493
- return { type: "text", nullable };
494
- }
495
- if (isAbiOptional(abiType))
496
- return mapType(abiType.optional, true);
497
- if (isAbiList(abiType) || isAbiTuple(abiType))
498
- return { type: "jsonb", nullable };
499
- if (isAbiResponse(abiType)) {
500
- return mapType(abiType.response.ok, nullable);
501
- }
502
- return { type: "jsonb", nullable };
503
- }
504
- function clarityTypeToSubgraphColumn(abiType) {
505
- return mapType(abiType, false);
506
- }
507
- function toSnake(name) {
508
- return name.replace(/-/g, "_");
509
- }
510
- function toCamel(name) {
511
- return name.replace(/-([a-z])/g, (_, c) => c.toUpperCase());
512
- }
513
- function buildColumns(args) {
514
- if (args.length === 0)
515
- return " _placeholder: { type: 'text' }";
516
- return args.map((arg) => {
517
- const mapped = clarityTypeToSubgraphColumn(arg.type);
518
- const nullable = mapped.nullable ? ", nullable: true" : "";
519
- return ` ${toSnake(arg.name)}: { type: '${mapped.type}'${nullable} }`;
520
- }).join(`,
521
- `);
522
- }
523
- function buildInsertCall(tableName, args) {
524
- if (args.length === 0) {
525
- return ` ctx.insert('${tableName}', {
526
- sender: ctx.tx.sender,
527
- });`;
528
- }
529
- const mappings = args.map((arg) => {
530
- return ` ${toSnake(arg.name)}: event.${toCamel(arg.name)}`;
531
- });
532
- return ` ctx.insert('${tableName}', {
533
- ${mappings.join(`,
534
- `)},
535
- });`;
536
- }
537
- function generateSubgraphCode(contractId, functions, subgraphName, events) {
538
- const contractParts = contractId.split(".");
539
- const contractName = contractParts[contractParts.length - 1] ?? contractId;
540
- const name = subgraphName ?? contractName;
541
- const publicFunctions = functions.filter((f) => f.access === "public");
542
- const hasEvents = events && events.length > 0;
543
- if (publicFunctions.length === 0 && !hasEvents) {
544
- return `// No public functions or events selected for ${contractId}`;
545
- }
546
- const tableDefs = [];
547
- if (hasEvents) {
548
- for (const ev of events) {
549
- const tableName = toSnake(ev.name);
550
- let columns;
551
- if (isAbiTuple(ev.value)) {
552
- columns = buildColumns(ev.value.tuple);
553
- } else {
554
- columns = ` value: { type: '${clarityTypeToSubgraphColumn(ev.value).type}' }`;
555
- }
556
- tableDefs.push(` ${tableName}: {
557
- columns: {
558
- ${columns}
559
- }
560
- }`);
561
- }
562
- }
563
- for (const fn of publicFunctions) {
564
- const tableName = toSnake(fn.name);
565
- const columns = buildColumns(fn.args);
566
- tableDefs.push(` ${tableName}: {
567
- columns: {
568
- ${columns}
569
- }
570
- }`);
571
- }
572
- const schemaBlock = tableDefs.join(`,
573
- `);
574
- const sourceEntries = [`{ contract: '${contractId}' }`];
575
- const handlerEntries = [];
576
- if (hasEvents) {
577
- for (const ev of events) {
578
- const tableName = toSnake(ev.name);
579
- let insertCall;
580
- if (isAbiTuple(ev.value)) {
581
- insertCall = buildInsertCall(tableName, ev.value.tuple);
582
- } else {
583
- insertCall = ` ctx.insert('${tableName}', {
584
- value: event.value,
585
- });`;
586
- }
587
- handlerEntries.push(` '${contractId}::${ev.name}': async (event, ctx) => {
588
- ${insertCall}
589
- }`);
590
- }
591
- }
592
- for (const fn of publicFunctions) {
593
- const tableName = toSnake(fn.name);
594
- const insertCall = buildInsertCall(tableName, fn.args);
595
- handlerEntries.push(` '${contractId}::${fn.name}': async (event, ctx) => {
596
- ${insertCall}
597
- }`);
598
- }
599
- const handlersBlock = handlerEntries.join(`,
600
-
601
- `);
602
- return `import { defineSubgraph } from '@secondlayer/subgraphs';
603
-
604
- export default defineSubgraph({
605
- name: '${name}',
606
- sources: [${sourceEntries.join(", ")}],
607
- schema: {
608
- ${schemaBlock}
609
- },
610
- handlers: {
611
- ${handlersBlock}
612
- }
613
- });
614
- `;
615
- }
616
-
617
- // src/tools/scaffold.ts
194
+ import { generateSubgraphCode } from "@secondlayer/scaffold";
195
+ import { z } from "zod/v4";
618
196
  var API_BASE = process.env.SECONDLAYER_API_URL || "https://api.secondlayer.tools";
619
197
  async function fetchAbi(contractId) {
620
198
  const res = await fetch(`${API_BASE}/api/node/contracts/${contractId}/abi`, {
@@ -633,17 +211,17 @@ async function fetchAbi(contractId) {
633
211
  }
634
212
  function registerScaffoldTools(server) {
635
213
  defineTool(server, "scaffold_from_contract", "Generate a subgraph scaffold from a deployed Stacks contract. Fetches the ABI automatically.", {
636
- contractId: z2.string().describe("Fully qualified contract ID (e.g. SP102V8P0F7JX67ARQ77WEA3D3CFB5XW39REDT0AM.amm-pool-v2-01)"),
637
- subgraphName: z2.string().optional().describe("Override the subgraph name (defaults to contract name)")
214
+ contractId: z.string().describe("Fully qualified contract ID (e.g. SP102V8P0F7JX67ARQ77WEA3D3CFB5XW39REDT0AM.amm-pool-v2-01)"),
215
+ subgraphName: z.string().optional().describe("Override the subgraph name (defaults to contract name)")
638
216
  }, async ({ contractId, subgraphName }) => {
639
217
  const { functions, maps } = await fetchAbi(contractId);
640
218
  const code = generateSubgraphCode(contractId, functions, subgraphName, maps);
641
219
  return { content: [{ type: "text", text: code }] };
642
220
  });
643
221
  defineTool(server, "scaffold_from_abi", "Generate a subgraph scaffold from a provided ABI JSON. Use when you already have the ABI.", {
644
- abi: z2.string().describe("ABI JSON string (the full contract ABI object)"),
645
- contractId: z2.string().describe("Fully qualified contract ID"),
646
- subgraphName: z2.string().optional().describe("Override the subgraph name")
222
+ abi: z.string().describe("ABI JSON string (the full contract ABI object)"),
223
+ contractId: z.string().describe("Fully qualified contract ID"),
224
+ subgraphName: z.string().optional().describe("Override the subgraph name")
647
225
  }, async ({ abi, contractId, subgraphName }) => {
648
226
  let parsed;
649
227
  try {
@@ -660,51 +238,8 @@ function registerScaffoldTools(server) {
660
238
  }
661
239
 
662
240
  // src/tools/subgraphs.ts
663
- import { z as z3 } from "zod/v4";
664
-
665
- // src/lib/bundle.ts
666
- import { validateSubgraphDefinition } from "@secondlayer/subgraphs/validate";
667
- import esbuild from "esbuild";
668
- async function bundleSubgraphCode(code) {
669
- let result;
670
- try {
671
- result = await esbuild.build({
672
- stdin: { contents: code, loader: "ts", resolveDir: process.cwd() },
673
- bundle: true,
674
- platform: "node",
675
- format: "esm",
676
- external: ["@secondlayer/subgraphs"],
677
- write: false
678
- });
679
- } catch (err) {
680
- throw new Error(`Bundle failed: ${err instanceof Error ? err.message : String(err)}`);
681
- }
682
- const handlerCode = new TextDecoder().decode(result.outputFiles[0].contents);
683
- let mod;
684
- try {
685
- const dataUri = `data:text/javascript;base64,${Buffer.from(handlerCode).toString("base64")}`;
686
- mod = await import(dataUri);
687
- } catch (err) {
688
- throw new Error(`Module evaluation failed: ${err instanceof Error ? err.message : String(err)}`);
689
- }
690
- const def = mod.default ?? mod;
691
- let validated;
692
- try {
693
- validated = validateSubgraphDefinition(def);
694
- } catch (err) {
695
- throw new Error(`Validation failed: ${err instanceof Error ? err.message : String(err)}`);
696
- }
697
- return {
698
- name: validated.name,
699
- version: validated.version,
700
- description: validated.description,
701
- sources: validated.sources,
702
- schema: validated.schema,
703
- handlerCode
704
- };
705
- }
706
-
707
- // src/tools/subgraphs.ts
241
+ import { bundleSubgraphCode } from "@secondlayer/bundler";
242
+ import { z as z2 } from "zod/v4";
708
243
  function registerSubgraphTools(server) {
709
244
  defineTool(server, "subgraphs_list", "List all deployed subgraphs. Returns summary fields only.", {}, async () => {
710
245
  const { data } = await getClient().subgraphs.list();
@@ -717,22 +252,22 @@ function registerSubgraphTools(server) {
717
252
  ]
718
253
  };
719
254
  });
720
- defineTool(server, "subgraphs_get", "Get full details of a subgraph including schema, health, and table columns.", { name: z3.string().describe("Subgraph name") }, async ({ name }) => {
255
+ defineTool(server, "subgraphs_get", "Get full details of a subgraph including schema, health, and table columns.", { name: z2.string().describe("Subgraph name") }, async ({ name }) => {
721
256
  const detail = await getClient().subgraphs.get(name);
722
257
  return {
723
258
  content: [{ type: "text", text: JSON.stringify(detail, null, 2) }]
724
259
  };
725
260
  });
726
261
  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.', {
727
- name: z3.string().describe("Subgraph name"),
728
- table: z3.string().describe("Table name"),
729
- filters: z3.record(z3.string(), z3.string()).optional().describe('Column filters — plain values or with operators (e.g. {"amount.gte": "1000", "sender": "SP..."})'),
730
- sort: z3.string().optional().describe("Column to sort by"),
731
- order: z3.enum(["asc", "desc"]).optional().describe("Sort order"),
732
- limit: z3.number().max(200).optional().describe("Max rows (default 50, max 200)"),
733
- offset: z3.number().optional().describe("Offset for pagination"),
734
- fields: z3.string().optional().describe('Comma-separated column list to return (e.g. "sender,amount")'),
735
- count: z3.boolean().optional().describe("If true, return row count instead of rows")
262
+ name: z2.string().describe("Subgraph name"),
263
+ table: z2.string().describe("Table name"),
264
+ filters: z2.record(z2.string(), z2.string()).optional().describe('Column filters — plain values or with operators (e.g. {"amount.gte": "1000", "sender": "SP..."})'),
265
+ sort: z2.string().optional().describe("Column to sort by"),
266
+ order: z2.enum(["asc", "desc"]).optional().describe("Sort order"),
267
+ limit: z2.number().max(200).optional().describe("Max rows (default 50, max 200)"),
268
+ offset: z2.number().optional().describe("Offset for pagination"),
269
+ fields: z2.string().optional().describe('Comma-separated column list to return (e.g. "sender,amount")'),
270
+ count: z2.boolean().optional().describe("If true, return row count instead of rows")
736
271
  }, async ({
737
272
  name,
738
273
  table,
@@ -765,9 +300,9 @@ function registerSubgraphTools(server) {
765
300
  };
766
301
  });
767
302
  defineTool(server, "subgraphs_reindex", "Reindex a subgraph from a specific block range.", {
768
- name: z3.string().describe("Subgraph name"),
769
- fromBlock: z3.number().optional().describe("Start block (defaults to beginning)"),
770
- toBlock: z3.number().optional().describe("End block (defaults to latest)")
303
+ name: z2.string().describe("Subgraph name"),
304
+ fromBlock: z2.number().optional().describe("Start block (defaults to beginning)"),
305
+ toBlock: z2.number().optional().describe("End block (defaults to latest)")
771
306
  }, async ({ name, fromBlock, toBlock }) => {
772
307
  const result = await getClient().subgraphs.reindex(name, {
773
308
  fromBlock,
@@ -777,13 +312,13 @@ function registerSubgraphTools(server) {
777
312
  content: [{ type: "text", text: JSON.stringify(result, null, 2) }]
778
313
  };
779
314
  });
780
- defineTool(server, "subgraphs_delete", "Delete a subgraph permanently.", { name: z3.string().describe("Subgraph name") }, async ({ name }) => {
315
+ defineTool(server, "subgraphs_delete", "Delete a subgraph permanently.", { name: z2.string().describe("Subgraph name") }, async ({ name }) => {
781
316
  const result = await getClient().subgraphs.delete(name);
782
317
  return { content: [{ type: "text", text: result.message }] };
783
318
  });
784
319
  defineTool(server, "subgraphs_deploy", "Deploy a subgraph from TypeScript code. Pass the full defineSubgraph() source — it will be bundled, validated, and deployed.", {
785
- code: z3.string().describe("TypeScript source code containing a defineSubgraph() call"),
786
- reindex: z3.boolean().optional().describe("Force reindex on breaking schema change (drops and rebuilds all data)")
320
+ code: z2.string().describe("TypeScript source code containing a defineSubgraph() call"),
321
+ reindex: z2.boolean().optional().describe("Force reindex on breaking schema change (drops and rebuilds all data)")
787
322
  }, async ({ code, reindex }) => {
788
323
  const bundled = await bundleSubgraphCode(code);
789
324
  const result = await getClient().subgraphs.deploy({
@@ -793,16 +328,33 @@ function registerSubgraphTools(server) {
793
328
  sources: bundled.sources,
794
329
  schema: bundled.schema,
795
330
  handlerCode: bundled.handlerCode,
331
+ sourceCode: code,
796
332
  reindex
797
333
  });
798
334
  return {
799
335
  content: [{ type: "text", text: JSON.stringify(result, null, 2) }]
800
336
  };
801
337
  });
338
+ 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: z2.string().describe("Subgraph name") }, async ({ name }) => {
339
+ const source = await getClient().subgraphs.getSource(name);
340
+ return {
341
+ content: [{ type: "text", text: JSON.stringify(source, null, 2) }]
342
+ };
343
+ });
802
344
  }
803
345
 
804
346
  // src/tools/workflows.ts
805
- import { z as z4 } from "zod/v4";
347
+ import { bundleWorkflowCode } from "@secondlayer/bundler";
348
+ import {
349
+ generateWorkflowCode
350
+ } from "@secondlayer/scaffold";
351
+ import { VersionConflictError } from "@secondlayer/sdk";
352
+ import {
353
+ getTemplateById as getWorkflowTemplateById,
354
+ templates as workflowTemplates2
355
+ } from "@secondlayer/workflows/templates";
356
+ import { createPatch } from "diff";
357
+ import { z as z3 } from "zod/v4";
806
358
  function registerWorkflowTools(server) {
807
359
  defineTool(server, "workflows_list", "List all workflows. Returns summary fields only.", {}, async () => {
808
360
  const { workflows } = await getClient().workflows.list();
@@ -815,15 +367,155 @@ function registerWorkflowTools(server) {
815
367
  ]
816
368
  };
817
369
  });
818
- defineTool(server, "workflows_get", "Get full details of a workflow by name.", { name: z4.string().describe("Workflow name") }, async ({ name }) => {
370
+ defineTool(server, "workflows_get", "Get full details of a workflow by name.", { name: z3.string().describe("Workflow name") }, async ({ name }) => {
819
371
  const detail = await getClient().workflows.get(name);
820
372
  return {
821
373
  content: [{ type: "text", text: JSON.stringify(detail, null, 2) }]
822
374
  };
823
375
  });
376
+ defineTool(server, "workflows_get_definition", "Return the deployed TypeScript source of a workflow plus its stored version. Returns `sourceCode: null` + `readOnly: true` for workflows deployed before source capture.", { name: z3.string().describe("Workflow name") }, async ({ name }) => {
377
+ const source = await getClient().workflows.getSource(name);
378
+ return {
379
+ content: [{ type: "text", text: JSON.stringify(source, null, 2) }]
380
+ };
381
+ });
382
+ defineTool(server, "workflows_propose_edit", "Validate a proposed edit WITHOUT deploying. Fetches the current stored source, bundles the proposed source, computes a unified diff, and returns everything for review. Use this when you want to show the user a diff before committing — pair it with workflows_deploy(expectedVersion=...) to persist.", {
383
+ name: z3.string().describe("Workflow name"),
384
+ proposedCode: z3.string().describe("New TypeScript source — must compile and validate."),
385
+ expectedVersion: z3.string().regex(/^\d+\.\d+\.\d+$/).optional().describe("Version the proposer is editing from (for audit).")
386
+ }, async ({ name, proposedCode, expectedVersion }) => {
387
+ const current = await getClient().workflows.getSource(name);
388
+ if (current.sourceCode === null) {
389
+ return {
390
+ isError: true,
391
+ content: [
392
+ {
393
+ type: "text",
394
+ text: JSON.stringify({
395
+ error: "Workflow has no stored source. Redeploy via CLI first.",
396
+ readOnly: true,
397
+ version: current.version
398
+ }, null, 2)
399
+ }
400
+ ]
401
+ };
402
+ }
403
+ let bundleValid = false;
404
+ let validation;
405
+ let bundleSize = 0;
406
+ try {
407
+ const bundled = await bundleWorkflowCode(proposedCode);
408
+ bundleValid = true;
409
+ bundleSize = Buffer.byteLength(bundled.handlerCode, "utf8");
410
+ validation = {
411
+ name: bundled.name,
412
+ triggerType: bundled.trigger.type
413
+ };
414
+ } catch (err) {
415
+ validation = {
416
+ error: err instanceof Error ? err.message : String(err)
417
+ };
418
+ }
419
+ const diffText = createPatch(`${name}.ts`, current.sourceCode, proposedCode, `v${current.version}`, "proposed");
420
+ return {
421
+ content: [
422
+ {
423
+ type: "text",
424
+ text: JSON.stringify({
425
+ currentVersion: current.version,
426
+ expectedVersion,
427
+ currentSource: current.sourceCode,
428
+ proposedSource: proposedCode,
429
+ diffText,
430
+ bundleValid,
431
+ validation,
432
+ bundleSize
433
+ }, null, 2)
434
+ }
435
+ ]
436
+ };
437
+ });
438
+ defineTool(server, "workflows_tail_run", "Tail a workflow run via SSE and return a compacted log. Resolves as soon as the run completes, `limit` events are collected, or `timeoutMs` elapses (default 60s). MCP is not streaming-first — use this for short-lived follow-ups, not long tails.", {
439
+ name: z3.string().describe("Workflow name"),
440
+ runId: z3.string().describe("Run id"),
441
+ limit: z3.number().int().positive().max(200).optional().describe("Max step events to collect (default 50)"),
442
+ timeoutMs: z3.number().int().positive().max(5 * 60 * 1000).optional().describe("Hard timeout in ms (default 60000, max 300000)")
443
+ }, async ({ name, runId, limit, timeoutMs }) => {
444
+ const cap = limit ?? 50;
445
+ const deadline = timeoutMs ?? 60000;
446
+ const events = [];
447
+ let finalStatus = null;
448
+ let stoppedBy = "timeout";
449
+ const controller = new AbortController;
450
+ const timer = setTimeout(() => {
451
+ stoppedBy = "timeout";
452
+ controller.abort();
453
+ }, deadline);
454
+ try {
455
+ await getClient().workflows.streamRun(name, runId, (event) => {
456
+ if (event.type === "step") {
457
+ events.push(event.step);
458
+ if (events.length >= cap) {
459
+ stoppedBy = "limit";
460
+ controller.abort();
461
+ }
462
+ } else if (event.type === "done") {
463
+ finalStatus = event.done.status;
464
+ stoppedBy = "done";
465
+ }
466
+ }, controller.signal);
467
+ } catch (err) {
468
+ if (!(err instanceof Error) || err.name !== "AbortError") {
469
+ throw err;
470
+ }
471
+ } finally {
472
+ clearTimeout(timer);
473
+ }
474
+ return {
475
+ content: [
476
+ {
477
+ type: "text",
478
+ text: JSON.stringify({
479
+ runId,
480
+ finalStatus,
481
+ stoppedBy,
482
+ eventCount: events.length,
483
+ events
484
+ }, null, 2)
485
+ }
486
+ ]
487
+ };
488
+ });
489
+ defineTool(server, "workflows_pause_all", "Pause ALL active workflows for the authenticated account. Irreversible only by calling pause/resume per workflow. Returns the list of affected workflows.", {}, async () => {
490
+ const result = await getClient().workflows.pauseAll();
491
+ return {
492
+ content: [{ type: "text", text: JSON.stringify(result, null, 2) }]
493
+ };
494
+ });
495
+ defineTool(server, "workflows_cancel_run", "Cancel an in-flight workflow run. Marks the run as cancelled and removes any pending queue entry. No-ops if the run is already terminal.", { runId: z3.string().describe("Run id to cancel") }, async ({ runId }) => {
496
+ const result = await getClient().workflows.cancelRun(runId);
497
+ return {
498
+ content: [{ type: "text", text: JSON.stringify(result, null, 2) }]
499
+ };
500
+ });
501
+ defineTool(server, "workflows_rollback", "Roll a workflow back to a prior version. The restored handler is re-published as a NEW version (audit trail), so no history is lost. Pass toVersion to pick a specific bundle; omit to roll back to the immediate previous version on disk. Last 3 versions are retained.", {
502
+ name: z3.string().describe("Workflow name"),
503
+ toVersion: z3.string().regex(/^\d+\.\d+\.\d+$/).optional().describe("Target version to restore. Must be one of the retained bundles on disk.")
504
+ }, async ({ name, toVersion }) => {
505
+ const result = await getClient().workflows.rollback(name, toVersion);
506
+ return {
507
+ content: [{ type: "text", text: JSON.stringify(result, null, 2) }]
508
+ };
509
+ });
510
+ defineTool(server, "workflows_delete", "Delete a workflow permanently.", { name: z3.string().describe("Workflow name") }, async ({ name }) => {
511
+ await getClient().workflows.delete(name);
512
+ return {
513
+ content: [{ type: "text", text: `Deleted workflow "${name}"` }]
514
+ };
515
+ });
824
516
  defineTool(server, "workflows_trigger", "Trigger a workflow run. Optionally pass input as a JSON string.", {
825
- name: z4.string().describe("Workflow name"),
826
- input: z4.string().optional().describe("Input as JSON string")
517
+ name: z3.string().describe("Workflow name"),
518
+ input: z3.string().optional().describe("Input as JSON string")
827
519
  }, async ({ name, input }) => {
828
520
  const parsed = input ? JSON.parse(input) : undefined;
829
521
  const result = await getClient().workflows.trigger(name, parsed);
@@ -831,22 +523,138 @@ function registerWorkflowTools(server) {
831
523
  content: [{ type: "text", text: JSON.stringify(result, null, 2) }]
832
524
  };
833
525
  });
834
- defineTool(server, "workflows_pause", "Pause a running workflow.", { name: z4.string().describe("Workflow name") }, async ({ name }) => {
526
+ defineTool(server, "workflows_pause", "Pause a running workflow.", { name: z3.string().describe("Workflow name") }, async ({ name }) => {
835
527
  await getClient().workflows.pause(name);
836
528
  return {
837
529
  content: [{ type: "text", text: `Paused workflow "${name}"` }]
838
530
  };
839
531
  });
840
- defineTool(server, "workflows_resume", "Resume a paused workflow.", { name: z4.string().describe("Workflow name") }, async ({ name }) => {
532
+ defineTool(server, "workflows_resume", "Resume a paused workflow.", { name: z3.string().describe("Workflow name") }, async ({ name }) => {
841
533
  await getClient().workflows.resume(name);
842
534
  return {
843
535
  content: [{ type: "text", text: `Resumed workflow "${name}"` }]
844
536
  };
845
537
  });
538
+ defineTool(server, "workflows_template_list", "List available workflow templates. Returns metadata only — use workflows_template_get for the full source.", {}, async () => {
539
+ return {
540
+ content: [
541
+ {
542
+ type: "text",
543
+ text: JSON.stringify(workflowTemplates2.map((t) => ({
544
+ id: t.id,
545
+ name: t.name,
546
+ description: t.description,
547
+ category: t.category,
548
+ trigger: t.trigger
549
+ })), null, 2)
550
+ }
551
+ ]
552
+ };
553
+ });
554
+ defineTool(server, "workflows_template_get", "Get a workflow template's full TypeScript source and prompt by id.", { id: z3.string().describe("Template id, e.g. 'whale-alert'") }, async ({ id }) => {
555
+ const template = getWorkflowTemplateById(id);
556
+ if (!template) {
557
+ return {
558
+ isError: true,
559
+ content: [
560
+ {
561
+ type: "text",
562
+ text: `Template "${id}" not found. Use workflows_template_list to see available templates.`
563
+ }
564
+ ]
565
+ };
566
+ }
567
+ return {
568
+ content: [
569
+ {
570
+ type: "text",
571
+ text: JSON.stringify(template, null, 2)
572
+ }
573
+ ]
574
+ };
575
+ });
576
+ defineTool(server, "workflows_scaffold", "Generate a compilable defineWorkflow() skeleton from a typed intent. Returns the TypeScript source; pass it to workflows_deploy to persist. Placeholders inside the source must be filled in before running a real workflow.", {
577
+ name: z3.string().regex(/^[a-z][a-z0-9-]*$/).describe("Workflow name (lowercase, hyphens)"),
578
+ trigger: z3.discriminatedUnion("type", [
579
+ z3.object({
580
+ type: z3.literal("event"),
581
+ filterType: z3.string().optional()
582
+ }),
583
+ z3.object({
584
+ type: z3.literal("schedule"),
585
+ cron: z3.string().min(1),
586
+ timezone: z3.string().optional()
587
+ }),
588
+ z3.object({ type: z3.literal("manual") })
589
+ ]).describe("Trigger shape"),
590
+ steps: z3.array(z3.enum(["run", "query", "ai", "deliver"])).describe("Ordered list of step kinds to include in the handler"),
591
+ deliveryTarget: z3.enum(["webhook", "slack", "email", "discord", "telegram"]).optional().describe("Delivery target used when steps includes `deliver`")
592
+ }, async ({ name, trigger, steps, deliveryTarget }) => {
593
+ const code = generateWorkflowCode({
594
+ name,
595
+ trigger,
596
+ steps,
597
+ deliveryTarget
598
+ });
599
+ return { content: [{ type: "text", text: code }] };
600
+ });
601
+ defineTool(server, "workflows_deploy", "Deploy a workflow from TypeScript source. Pass the full defineWorkflow() source — it will be bundled, validated, and deployed. Use expectedVersion for optimistic concurrency, or dryRun to validate without persisting.", {
602
+ code: z3.string().describe("TypeScript source code containing a defineWorkflow() call"),
603
+ expectedVersion: z3.string().regex(/^\d+\.\d+\.\d+$/).optional().describe("Stored version the client expects (major.minor.patch). Server returns 409 on mismatch."),
604
+ dryRun: z3.boolean().optional().describe("If true, validate and bundle only — do not persist.")
605
+ }, async ({ code, expectedVersion, dryRun }) => {
606
+ let bundled;
607
+ try {
608
+ bundled = await bundleWorkflowCode(code);
609
+ } catch (err) {
610
+ return {
611
+ isError: true,
612
+ content: [
613
+ {
614
+ type: "text",
615
+ text: err instanceof Error ? err.message : String(err)
616
+ }
617
+ ]
618
+ };
619
+ }
620
+ const base = {
621
+ name: bundled.name,
622
+ trigger: bundled.trigger,
623
+ handlerCode: bundled.handlerCode,
624
+ sourceCode: bundled.sourceCode,
625
+ retries: bundled.retries,
626
+ timeout: bundled.timeout,
627
+ expectedVersion
628
+ };
629
+ try {
630
+ const result = dryRun ? await getClient().workflows.deploy({ ...base, dryRun: true }) : await getClient().workflows.deploy(base);
631
+ return {
632
+ content: [{ type: "text", text: JSON.stringify(result, null, 2) }]
633
+ };
634
+ } catch (err) {
635
+ if (err instanceof VersionConflictError) {
636
+ return {
637
+ isError: true,
638
+ content: [
639
+ {
640
+ type: "text",
641
+ text: JSON.stringify({
642
+ error: err.message,
643
+ code: "VERSION_CONFLICT",
644
+ currentVersion: err.currentVersion,
645
+ expectedVersion: err.expectedVersion
646
+ }, null, 2)
647
+ }
648
+ ]
649
+ };
650
+ }
651
+ throw err;
652
+ }
653
+ });
846
654
  defineTool(server, "workflows_runs", "List runs for a workflow. Optionally filter by status and limit results.", {
847
- name: z4.string().describe("Workflow name"),
848
- status: z4.enum(["running", "completed", "failed", "cancelled"]).optional().describe("Filter by run status"),
849
- limit: z4.number().optional().describe("Max runs to return (default 20)")
655
+ name: z3.string().describe("Workflow name"),
656
+ status: z3.enum(["running", "completed", "failed", "cancelled"]).optional().describe("Filter by run status"),
657
+ limit: z3.number().optional().describe("Max runs to return (default 20)")
850
658
  }, async ({ name, status, limit }) => {
851
659
  const { runs } = await getClient().workflows.listRuns(name, {
852
660
  status,
@@ -867,14 +675,14 @@ function registerWorkflowTools(server) {
867
675
  import {
868
676
  getTemplateById,
869
677
  getTemplatesByCategory,
870
- templates as templates2
678
+ templates
871
679
  } from "@secondlayer/subgraphs/templates";
872
- import { z as z5 } from "zod/v4";
680
+ import { z as z4 } from "zod/v4";
873
681
  function registerTemplateTools(server) {
874
682
  defineTool(server, "templates_list", "List available subgraph templates. Returns metadata only — use templates_get for full code.", {
875
- category: z5.enum(["defi", "nft", "token", "infrastructure"]).optional().describe("Filter by category")
683
+ category: z4.enum(["defi", "nft", "token", "infrastructure"]).optional().describe("Filter by category")
876
684
  }, async ({ category }) => {
877
- const list = category ? getTemplatesByCategory(category) : templates2;
685
+ const list = category ? getTemplatesByCategory(category) : templates;
878
686
  return {
879
687
  content: [
880
688
  {
@@ -889,7 +697,7 @@ function registerTemplateTools(server) {
889
697
  ]
890
698
  };
891
699
  });
892
- defineTool(server, "templates_get", "Get a template's full code and prompt by ID.", { id: z5.string().describe("Template ID (e.g. 'dex-swaps')") }, async ({ id }) => {
700
+ defineTool(server, "templates_get", "Get a template's full code and prompt by ID.", { id: z4.string().describe("Template ID (e.g. 'dex-swaps')") }, async ({ id }) => {
893
701
  const template = getTemplateById(id);
894
702
  if (!template) {
895
703
  return {
@@ -930,7 +738,6 @@ function createServer() {
930
738
  });
931
739
  registerTemplateTools(server);
932
740
  registerScaffoldTools(server);
933
- registerStreamTools(server);
934
741
  registerSubgraphTools(server);
935
742
  registerAccountTools(server);
936
743
  registerWorkflowTools(server);
@@ -941,5 +748,5 @@ export {
941
748
  createServer
942
749
  };
943
750
 
944
- //# debugId=8518CB4307D6FCD664756E2164756E21
751
+ //# debugId=6CB2325BA11B0F2F64756E2164756E21
945
752
  //# sourceMappingURL=index.js.map