@secondlayer/mcp 0.4.2 → 1.0.1
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 +3 -6
- package/dist/bin-http.js +351 -658
- package/dist/bin-http.js.map +11 -15
- package/dist/bin.js +351 -658
- package/dist/bin.js.map +11 -15
- package/dist/index.js +351 -658
- package/dist/index.js.map +11 -15
- package/package.json +8 -5
package/dist/index.js
CHANGED
|
@@ -5,10 +5,80 @@ import { fileURLToPath } from "node:url";
|
|
|
5
5
|
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
6
6
|
|
|
7
7
|
// src/resources.ts
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
8
|
+
var FILTERS_REFERENCE = [
|
|
9
|
+
{
|
|
10
|
+
type: "stx_transfer",
|
|
11
|
+
fields: ["sender", "recipient", "minAmount", "maxAmount"]
|
|
12
|
+
},
|
|
13
|
+
{ type: "stx_mint", fields: ["recipient", "minAmount"] },
|
|
14
|
+
{ type: "stx_burn", fields: ["sender", "minAmount"] },
|
|
15
|
+
{ type: "stx_lock", fields: ["lockedAddress", "minAmount"] },
|
|
16
|
+
{
|
|
17
|
+
type: "ft_transfer",
|
|
18
|
+
fields: [
|
|
19
|
+
"sender",
|
|
20
|
+
"recipient",
|
|
21
|
+
"assetIdentifier",
|
|
22
|
+
"minAmount",
|
|
23
|
+
"maxAmount"
|
|
24
|
+
]
|
|
25
|
+
},
|
|
26
|
+
{ type: "ft_mint", fields: ["recipient", "assetIdentifier", "minAmount"] },
|
|
27
|
+
{ type: "ft_burn", fields: ["sender", "assetIdentifier", "minAmount"] },
|
|
28
|
+
{
|
|
29
|
+
type: "nft_transfer",
|
|
30
|
+
fields: ["sender", "recipient", "assetIdentifier", "tokenId"]
|
|
31
|
+
},
|
|
32
|
+
{ type: "nft_mint", fields: ["recipient", "assetIdentifier", "tokenId"] },
|
|
33
|
+
{ type: "nft_burn", fields: ["sender", "assetIdentifier", "tokenId"] },
|
|
34
|
+
{ type: "contract_call", fields: ["contract", "function"] },
|
|
35
|
+
{ type: "contract_deploy", fields: ["contract"] },
|
|
36
|
+
{ type: "print_event", fields: ["contract", "event", "contains"] }
|
|
37
|
+
];
|
|
38
|
+
var COLUMN_TYPES = [
|
|
39
|
+
{
|
|
40
|
+
type: "uint",
|
|
41
|
+
sqlType: "bigint",
|
|
42
|
+
description: "Unsigned integer (Clarity uint)"
|
|
43
|
+
},
|
|
44
|
+
{
|
|
45
|
+
type: "int",
|
|
46
|
+
sqlType: "bigint",
|
|
47
|
+
description: "Signed integer (Clarity int)"
|
|
48
|
+
},
|
|
49
|
+
{ type: "text", sqlType: "text", description: "UTF-8 string" },
|
|
50
|
+
{
|
|
51
|
+
type: "principal",
|
|
52
|
+
sqlType: "text",
|
|
53
|
+
description: "Stacks address (standard or contract)"
|
|
54
|
+
},
|
|
55
|
+
{ type: "bool", sqlType: "boolean", description: "Boolean value" },
|
|
56
|
+
{ type: "json", sqlType: "jsonb", description: "Arbitrary JSON data" },
|
|
57
|
+
{
|
|
58
|
+
options: ["nullable", "indexed", "search"],
|
|
59
|
+
description: "Column options: nullable allows NULL, indexed creates a B-tree index, search enables full-text search"
|
|
60
|
+
}
|
|
61
|
+
];
|
|
62
|
+
function registerResources(server) {
|
|
63
|
+
server.resource("filters", "secondlayer://filters", { description: "Event filter types and their available fields" }, async () => ({
|
|
64
|
+
contents: [
|
|
65
|
+
{
|
|
66
|
+
uri: "secondlayer://filters",
|
|
67
|
+
mimeType: "application/json",
|
|
68
|
+
text: JSON.stringify(FILTERS_REFERENCE, null, 2)
|
|
69
|
+
}
|
|
70
|
+
]
|
|
71
|
+
}));
|
|
72
|
+
server.resource("column-types", "secondlayer://column-types", { description: "Subgraph column types, SQL mappings, and options" }, async () => ({
|
|
73
|
+
contents: [
|
|
74
|
+
{
|
|
75
|
+
uri: "secondlayer://column-types",
|
|
76
|
+
mimeType: "application/json",
|
|
77
|
+
text: JSON.stringify(COLUMN_TYPES, null, 2)
|
|
78
|
+
}
|
|
79
|
+
]
|
|
80
|
+
}));
|
|
81
|
+
}
|
|
12
82
|
|
|
13
83
|
// src/lib/client.ts
|
|
14
84
|
import { SecondLayer } from "@secondlayer/sdk";
|
|
@@ -19,7 +89,12 @@ function getClient() {
|
|
|
19
89
|
if (!apiKey) {
|
|
20
90
|
throw new Error("SECONDLAYER_API_KEY environment variable is required. " + "Get your key at https://app.secondlayer.tools/settings/api-keys");
|
|
21
91
|
}
|
|
22
|
-
|
|
92
|
+
const baseUrl = process.env.SECONDLAYER_API_URL;
|
|
93
|
+
instance = new SecondLayer({
|
|
94
|
+
apiKey,
|
|
95
|
+
origin: "mcp",
|
|
96
|
+
...baseUrl ? { baseUrl } : {}
|
|
97
|
+
});
|
|
23
98
|
}
|
|
24
99
|
return instance;
|
|
25
100
|
}
|
|
@@ -48,16 +123,6 @@ async function apiRequest(method, path, body) {
|
|
|
48
123
|
}
|
|
49
124
|
|
|
50
125
|
// 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
126
|
function formatSubgraphSummary(s) {
|
|
62
127
|
return {
|
|
63
128
|
name: s.name,
|
|
@@ -66,16 +131,6 @@ function formatSubgraphSummary(s) {
|
|
|
66
131
|
lastProcessedBlock: s.lastProcessedBlock
|
|
67
132
|
};
|
|
68
133
|
}
|
|
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
134
|
function withCap(items, cap) {
|
|
80
135
|
return {
|
|
81
136
|
items: items.slice(0, cap),
|
|
@@ -83,6 +138,12 @@ function withCap(items, cap) {
|
|
|
83
138
|
total: items.length
|
|
84
139
|
};
|
|
85
140
|
}
|
|
141
|
+
function jsonResponse(data, isError) {
|
|
142
|
+
return {
|
|
143
|
+
content: [{ type: "text", text: JSON.stringify(data, null, 2) }],
|
|
144
|
+
...isError && { isError: true }
|
|
145
|
+
};
|
|
146
|
+
}
|
|
86
147
|
|
|
87
148
|
// src/lib/tool.ts
|
|
88
149
|
function defineTool(server, name, description, schema, handler) {
|
|
@@ -107,514 +168,17 @@ function defineTool(server, name, description, schema, handler) {
|
|
|
107
168
|
server.tool(name, description, schema, wrappedHandler);
|
|
108
169
|
}
|
|
109
170
|
|
|
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
171
|
// src/tools/account.ts
|
|
429
172
|
function registerAccountTools(server) {
|
|
430
173
|
defineTool(server, "account_whoami", "Show the authenticated account's email and plan.", {}, async () => {
|
|
431
174
|
const result = await apiRequest("GET", "/api/accounts/me");
|
|
432
|
-
return
|
|
433
|
-
content: [{ type: "text", text: JSON.stringify(result, null, 2) }]
|
|
434
|
-
};
|
|
175
|
+
return jsonResponse(result);
|
|
435
176
|
});
|
|
436
177
|
}
|
|
437
178
|
|
|
438
179
|
// src/tools/scaffold.ts
|
|
439
|
-
import {
|
|
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
|
|
180
|
+
import { generateSubgraphCode } from "@secondlayer/scaffold";
|
|
181
|
+
import { z } from "zod/v4";
|
|
618
182
|
var API_BASE = process.env.SECONDLAYER_API_URL || "https://api.secondlayer.tools";
|
|
619
183
|
async function fetchAbi(contractId) {
|
|
620
184
|
const res = await fetch(`${API_BASE}/api/node/contracts/${contractId}/abi`, {
|
|
@@ -633,17 +197,17 @@ async function fetchAbi(contractId) {
|
|
|
633
197
|
}
|
|
634
198
|
function registerScaffoldTools(server) {
|
|
635
199
|
defineTool(server, "scaffold_from_contract", "Generate a subgraph scaffold from a deployed Stacks contract. Fetches the ABI automatically.", {
|
|
636
|
-
contractId:
|
|
637
|
-
subgraphName:
|
|
200
|
+
contractId: z.string().describe("Fully qualified contract ID (e.g. SP102V8P0F7JX67ARQ77WEA3D3CFB5XW39REDT0AM.amm-pool-v2-01)"),
|
|
201
|
+
subgraphName: z.string().optional().describe("Override the subgraph name (defaults to contract name)")
|
|
638
202
|
}, async ({ contractId, subgraphName }) => {
|
|
639
203
|
const { functions, maps } = await fetchAbi(contractId);
|
|
640
204
|
const code = generateSubgraphCode(contractId, functions, subgraphName, maps);
|
|
641
205
|
return { content: [{ type: "text", text: code }] };
|
|
642
206
|
});
|
|
643
207
|
defineTool(server, "scaffold_from_abi", "Generate a subgraph scaffold from a provided ABI JSON. Use when you already have the ABI.", {
|
|
644
|
-
abi:
|
|
645
|
-
contractId:
|
|
646
|
-
subgraphName:
|
|
208
|
+
abi: z.string().describe("ABI JSON string (the full contract ABI object)"),
|
|
209
|
+
contractId: z.string().describe("Fully qualified contract ID"),
|
|
210
|
+
subgraphName: z.string().optional().describe("Override the subgraph name")
|
|
647
211
|
}, async ({ abi, contractId, subgraphName }) => {
|
|
648
212
|
let parsed;
|
|
649
213
|
try {
|
|
@@ -660,51 +224,8 @@ function registerScaffoldTools(server) {
|
|
|
660
224
|
}
|
|
661
225
|
|
|
662
226
|
// src/tools/subgraphs.ts
|
|
663
|
-
import {
|
|
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
|
|
227
|
+
import { bundleSubgraphCode } from "@secondlayer/bundler";
|
|
228
|
+
import { z as z2 } from "zod/v4";
|
|
708
229
|
function registerSubgraphTools(server) {
|
|
709
230
|
defineTool(server, "subgraphs_list", "List all deployed subgraphs. Returns summary fields only.", {}, async () => {
|
|
710
231
|
const { data } = await getClient().subgraphs.list();
|
|
@@ -717,22 +238,22 @@ function registerSubgraphTools(server) {
|
|
|
717
238
|
]
|
|
718
239
|
};
|
|
719
240
|
});
|
|
720
|
-
defineTool(server, "subgraphs_get", "Get full details of a subgraph including schema, health, and table columns.", { name:
|
|
241
|
+
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
242
|
const detail = await getClient().subgraphs.get(name);
|
|
722
243
|
return {
|
|
723
244
|
content: [{ type: "text", text: JSON.stringify(detail, null, 2) }]
|
|
724
245
|
};
|
|
725
246
|
});
|
|
726
247
|
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:
|
|
728
|
-
table:
|
|
729
|
-
filters:
|
|
730
|
-
sort:
|
|
731
|
-
order:
|
|
732
|
-
limit:
|
|
733
|
-
offset:
|
|
734
|
-
fields:
|
|
735
|
-
count:
|
|
248
|
+
name: z2.string().describe("Subgraph name"),
|
|
249
|
+
table: z2.string().describe("Table name"),
|
|
250
|
+
filters: z2.record(z2.string(), z2.string()).optional().describe('Column filters — plain values or with operators (e.g. {"amount.gte": "1000", "sender": "SP..."})'),
|
|
251
|
+
sort: z2.string().optional().describe("Column to sort by"),
|
|
252
|
+
order: z2.enum(["asc", "desc"]).optional().describe("Sort order"),
|
|
253
|
+
limit: z2.number().max(200).optional().describe("Max rows (default 50, max 200)"),
|
|
254
|
+
offset: z2.number().optional().describe("Offset for pagination"),
|
|
255
|
+
fields: z2.string().optional().describe('Comma-separated column list to return (e.g. "sender,amount")'),
|
|
256
|
+
count: z2.boolean().optional().describe("If true, return row count instead of rows")
|
|
736
257
|
}, async ({
|
|
737
258
|
name,
|
|
738
259
|
table,
|
|
@@ -765,9 +286,9 @@ function registerSubgraphTools(server) {
|
|
|
765
286
|
};
|
|
766
287
|
});
|
|
767
288
|
defineTool(server, "subgraphs_reindex", "Reindex a subgraph from a specific block range.", {
|
|
768
|
-
name:
|
|
769
|
-
fromBlock:
|
|
770
|
-
toBlock:
|
|
289
|
+
name: z2.string().describe("Subgraph name"),
|
|
290
|
+
fromBlock: z2.number().optional().describe("Start block (defaults to beginning)"),
|
|
291
|
+
toBlock: z2.number().optional().describe("End block (defaults to latest)")
|
|
771
292
|
}, async ({ name, fromBlock, toBlock }) => {
|
|
772
293
|
const result = await getClient().subgraphs.reindex(name, {
|
|
773
294
|
fromBlock,
|
|
@@ -777,13 +298,13 @@ function registerSubgraphTools(server) {
|
|
|
777
298
|
content: [{ type: "text", text: JSON.stringify(result, null, 2) }]
|
|
778
299
|
};
|
|
779
300
|
});
|
|
780
|
-
defineTool(server, "subgraphs_delete", "Delete a subgraph permanently.", { name:
|
|
301
|
+
defineTool(server, "subgraphs_delete", "Delete a subgraph permanently.", { name: z2.string().describe("Subgraph name") }, async ({ name }) => {
|
|
781
302
|
const result = await getClient().subgraphs.delete(name);
|
|
782
303
|
return { content: [{ type: "text", text: result.message }] };
|
|
783
304
|
});
|
|
784
305
|
defineTool(server, "subgraphs_deploy", "Deploy a subgraph from TypeScript code. Pass the full defineSubgraph() source — it will be bundled, validated, and deployed.", {
|
|
785
|
-
code:
|
|
786
|
-
reindex:
|
|
306
|
+
code: z2.string().describe("TypeScript source code containing a defineSubgraph() call"),
|
|
307
|
+
reindex: z2.boolean().optional().describe("Force reindex on breaking schema change (drops and rebuilds all data)")
|
|
787
308
|
}, async ({ code, reindex }) => {
|
|
788
309
|
const bundled = await bundleSubgraphCode(code);
|
|
789
310
|
const result = await getClient().subgraphs.deploy({
|
|
@@ -793,16 +314,29 @@ function registerSubgraphTools(server) {
|
|
|
793
314
|
sources: bundled.sources,
|
|
794
315
|
schema: bundled.schema,
|
|
795
316
|
handlerCode: bundled.handlerCode,
|
|
317
|
+
sourceCode: code,
|
|
796
318
|
reindex
|
|
797
319
|
});
|
|
798
320
|
return {
|
|
799
321
|
content: [{ type: "text", text: JSON.stringify(result, null, 2) }]
|
|
800
322
|
};
|
|
801
323
|
});
|
|
324
|
+
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 }) => {
|
|
325
|
+
const source = await getClient().subgraphs.getSource(name);
|
|
326
|
+
return {
|
|
327
|
+
content: [{ type: "text", text: JSON.stringify(source, null, 2) }]
|
|
328
|
+
};
|
|
329
|
+
});
|
|
802
330
|
}
|
|
803
331
|
|
|
804
332
|
// src/tools/workflows.ts
|
|
805
|
-
import {
|
|
333
|
+
import { bundleWorkflowCode } from "@secondlayer/bundler";
|
|
334
|
+
import {
|
|
335
|
+
generateWorkflowCode
|
|
336
|
+
} from "@secondlayer/scaffold";
|
|
337
|
+
import { VersionConflictError } from "@secondlayer/sdk";
|
|
338
|
+
import { createPatch } from "diff";
|
|
339
|
+
import { z as z3 } from "zod/v4";
|
|
806
340
|
function registerWorkflowTools(server) {
|
|
807
341
|
defineTool(server, "workflows_list", "List all workflows. Returns summary fields only.", {}, async () => {
|
|
808
342
|
const { workflows } = await getClient().workflows.list();
|
|
@@ -815,15 +349,155 @@ function registerWorkflowTools(server) {
|
|
|
815
349
|
]
|
|
816
350
|
};
|
|
817
351
|
});
|
|
818
|
-
defineTool(server, "workflows_get", "Get full details of a workflow by name.", { name:
|
|
352
|
+
defineTool(server, "workflows_get", "Get full details of a workflow by name.", { name: z3.string().describe("Workflow name") }, async ({ name }) => {
|
|
819
353
|
const detail = await getClient().workflows.get(name);
|
|
820
354
|
return {
|
|
821
355
|
content: [{ type: "text", text: JSON.stringify(detail, null, 2) }]
|
|
822
356
|
};
|
|
823
357
|
});
|
|
358
|
+
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 }) => {
|
|
359
|
+
const source = await getClient().workflows.getSource(name);
|
|
360
|
+
return {
|
|
361
|
+
content: [{ type: "text", text: JSON.stringify(source, null, 2) }]
|
|
362
|
+
};
|
|
363
|
+
});
|
|
364
|
+
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.", {
|
|
365
|
+
name: z3.string().describe("Workflow name"),
|
|
366
|
+
proposedCode: z3.string().describe("New TypeScript source — must compile and validate."),
|
|
367
|
+
expectedVersion: z3.string().regex(/^\d+\.\d+\.\d+$/).optional().describe("Version the proposer is editing from (for audit).")
|
|
368
|
+
}, async ({ name, proposedCode, expectedVersion }) => {
|
|
369
|
+
const current = await getClient().workflows.getSource(name);
|
|
370
|
+
if (current.sourceCode === null) {
|
|
371
|
+
return {
|
|
372
|
+
isError: true,
|
|
373
|
+
content: [
|
|
374
|
+
{
|
|
375
|
+
type: "text",
|
|
376
|
+
text: JSON.stringify({
|
|
377
|
+
error: "Workflow has no stored source. Redeploy via CLI first.",
|
|
378
|
+
readOnly: true,
|
|
379
|
+
version: current.version
|
|
380
|
+
}, null, 2)
|
|
381
|
+
}
|
|
382
|
+
]
|
|
383
|
+
};
|
|
384
|
+
}
|
|
385
|
+
let bundleValid = false;
|
|
386
|
+
let validation;
|
|
387
|
+
let bundleSize = 0;
|
|
388
|
+
try {
|
|
389
|
+
const bundled = await bundleWorkflowCode(proposedCode);
|
|
390
|
+
bundleValid = true;
|
|
391
|
+
bundleSize = Buffer.byteLength(bundled.handlerCode, "utf8");
|
|
392
|
+
validation = {
|
|
393
|
+
name: bundled.name,
|
|
394
|
+
triggerType: bundled.trigger.type
|
|
395
|
+
};
|
|
396
|
+
} catch (err) {
|
|
397
|
+
validation = {
|
|
398
|
+
error: err instanceof Error ? err.message : String(err)
|
|
399
|
+
};
|
|
400
|
+
}
|
|
401
|
+
const diffText = createPatch(`${name}.ts`, current.sourceCode, proposedCode, `v${current.version}`, "proposed");
|
|
402
|
+
return {
|
|
403
|
+
content: [
|
|
404
|
+
{
|
|
405
|
+
type: "text",
|
|
406
|
+
text: JSON.stringify({
|
|
407
|
+
currentVersion: current.version,
|
|
408
|
+
expectedVersion,
|
|
409
|
+
currentSource: current.sourceCode,
|
|
410
|
+
proposedSource: proposedCode,
|
|
411
|
+
diffText,
|
|
412
|
+
bundleValid,
|
|
413
|
+
validation,
|
|
414
|
+
bundleSize
|
|
415
|
+
}, null, 2)
|
|
416
|
+
}
|
|
417
|
+
]
|
|
418
|
+
};
|
|
419
|
+
});
|
|
420
|
+
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.", {
|
|
421
|
+
name: z3.string().describe("Workflow name"),
|
|
422
|
+
runId: z3.string().describe("Run id"),
|
|
423
|
+
limit: z3.number().int().positive().max(200).optional().describe("Max step events to collect (default 50)"),
|
|
424
|
+
timeoutMs: z3.number().int().positive().max(5 * 60 * 1000).optional().describe("Hard timeout in ms (default 60000, max 300000)")
|
|
425
|
+
}, async ({ name, runId, limit, timeoutMs }) => {
|
|
426
|
+
const cap = limit ?? 50;
|
|
427
|
+
const deadline = timeoutMs ?? 60000;
|
|
428
|
+
const events = [];
|
|
429
|
+
let finalStatus = null;
|
|
430
|
+
let stoppedBy = "timeout";
|
|
431
|
+
const controller = new AbortController;
|
|
432
|
+
const timer = setTimeout(() => {
|
|
433
|
+
stoppedBy = "timeout";
|
|
434
|
+
controller.abort();
|
|
435
|
+
}, deadline);
|
|
436
|
+
try {
|
|
437
|
+
await getClient().workflows.streamRun(name, runId, (event) => {
|
|
438
|
+
if (event.type === "step") {
|
|
439
|
+
events.push(event.step);
|
|
440
|
+
if (events.length >= cap) {
|
|
441
|
+
stoppedBy = "limit";
|
|
442
|
+
controller.abort();
|
|
443
|
+
}
|
|
444
|
+
} else if (event.type === "done") {
|
|
445
|
+
finalStatus = event.done.status;
|
|
446
|
+
stoppedBy = "done";
|
|
447
|
+
}
|
|
448
|
+
}, controller.signal);
|
|
449
|
+
} catch (err) {
|
|
450
|
+
if (!(err instanceof Error) || err.name !== "AbortError") {
|
|
451
|
+
throw err;
|
|
452
|
+
}
|
|
453
|
+
} finally {
|
|
454
|
+
clearTimeout(timer);
|
|
455
|
+
}
|
|
456
|
+
return {
|
|
457
|
+
content: [
|
|
458
|
+
{
|
|
459
|
+
type: "text",
|
|
460
|
+
text: JSON.stringify({
|
|
461
|
+
runId,
|
|
462
|
+
finalStatus,
|
|
463
|
+
stoppedBy,
|
|
464
|
+
eventCount: events.length,
|
|
465
|
+
events
|
|
466
|
+
}, null, 2)
|
|
467
|
+
}
|
|
468
|
+
]
|
|
469
|
+
};
|
|
470
|
+
});
|
|
471
|
+
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 () => {
|
|
472
|
+
const result = await getClient().workflows.pauseAll();
|
|
473
|
+
return {
|
|
474
|
+
content: [{ type: "text", text: JSON.stringify(result, null, 2) }]
|
|
475
|
+
};
|
|
476
|
+
});
|
|
477
|
+
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 }) => {
|
|
478
|
+
const result = await getClient().workflows.cancelRun(runId);
|
|
479
|
+
return {
|
|
480
|
+
content: [{ type: "text", text: JSON.stringify(result, null, 2) }]
|
|
481
|
+
};
|
|
482
|
+
});
|
|
483
|
+
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.", {
|
|
484
|
+
name: z3.string().describe("Workflow name"),
|
|
485
|
+
toVersion: z3.string().regex(/^\d+\.\d+\.\d+$/).optional().describe("Target version to restore. Must be one of the retained bundles on disk.")
|
|
486
|
+
}, async ({ name, toVersion }) => {
|
|
487
|
+
const result = await getClient().workflows.rollback(name, toVersion);
|
|
488
|
+
return {
|
|
489
|
+
content: [{ type: "text", text: JSON.stringify(result, null, 2) }]
|
|
490
|
+
};
|
|
491
|
+
});
|
|
492
|
+
defineTool(server, "workflows_delete", "Delete a workflow permanently.", { name: z3.string().describe("Workflow name") }, async ({ name }) => {
|
|
493
|
+
await getClient().workflows.delete(name);
|
|
494
|
+
return {
|
|
495
|
+
content: [{ type: "text", text: `Deleted workflow "${name}"` }]
|
|
496
|
+
};
|
|
497
|
+
});
|
|
824
498
|
defineTool(server, "workflows_trigger", "Trigger a workflow run. Optionally pass input as a JSON string.", {
|
|
825
|
-
name:
|
|
826
|
-
input:
|
|
499
|
+
name: z3.string().describe("Workflow name"),
|
|
500
|
+
input: z3.string().optional().describe("Input as JSON string")
|
|
827
501
|
}, async ({ name, input }) => {
|
|
828
502
|
const parsed = input ? JSON.parse(input) : undefined;
|
|
829
503
|
const result = await getClient().workflows.trigger(name, parsed);
|
|
@@ -831,89 +505,110 @@ function registerWorkflowTools(server) {
|
|
|
831
505
|
content: [{ type: "text", text: JSON.stringify(result, null, 2) }]
|
|
832
506
|
};
|
|
833
507
|
});
|
|
834
|
-
defineTool(server, "workflows_pause", "Pause a running workflow.", { name:
|
|
508
|
+
defineTool(server, "workflows_pause", "Pause a running workflow.", { name: z3.string().describe("Workflow name") }, async ({ name }) => {
|
|
835
509
|
await getClient().workflows.pause(name);
|
|
836
510
|
return {
|
|
837
511
|
content: [{ type: "text", text: `Paused workflow "${name}"` }]
|
|
838
512
|
};
|
|
839
513
|
});
|
|
840
|
-
defineTool(server, "workflows_resume", "Resume a paused workflow.", { name:
|
|
514
|
+
defineTool(server, "workflows_resume", "Resume a paused workflow.", { name: z3.string().describe("Workflow name") }, async ({ name }) => {
|
|
841
515
|
await getClient().workflows.resume(name);
|
|
842
516
|
return {
|
|
843
517
|
content: [{ type: "text", text: `Resumed workflow "${name}"` }]
|
|
844
518
|
};
|
|
845
519
|
});
|
|
846
|
-
defineTool(server, "
|
|
847
|
-
name:
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
|
|
852
|
-
|
|
853
|
-
|
|
520
|
+
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.", {
|
|
521
|
+
name: z3.string().regex(/^[a-z][a-z0-9-]*$/).describe("Workflow name (lowercase, hyphens)"),
|
|
522
|
+
trigger: z3.discriminatedUnion("type", [
|
|
523
|
+
z3.object({
|
|
524
|
+
type: z3.literal("event"),
|
|
525
|
+
filterType: z3.string().optional()
|
|
526
|
+
}),
|
|
527
|
+
z3.object({
|
|
528
|
+
type: z3.literal("schedule"),
|
|
529
|
+
cron: z3.string().min(1),
|
|
530
|
+
timezone: z3.string().optional()
|
|
531
|
+
}),
|
|
532
|
+
z3.object({ type: z3.literal("manual") })
|
|
533
|
+
]).describe("Trigger shape"),
|
|
534
|
+
steps: z3.array(z3.enum(["run", "query", "ai", "deliver"])).describe("Ordered list of step kinds to include in the handler"),
|
|
535
|
+
deliveryTarget: z3.enum(["webhook", "slack", "email", "discord", "telegram"]).optional().describe("Delivery target used when steps includes `deliver`")
|
|
536
|
+
}, async ({ name, trigger, steps, deliveryTarget }) => {
|
|
537
|
+
const code = generateWorkflowCode({
|
|
538
|
+
name,
|
|
539
|
+
trigger,
|
|
540
|
+
steps,
|
|
541
|
+
deliveryTarget
|
|
854
542
|
});
|
|
855
|
-
return {
|
|
856
|
-
content: [
|
|
857
|
-
{
|
|
858
|
-
type: "text",
|
|
859
|
-
text: JSON.stringify(runs, null, 2)
|
|
860
|
-
}
|
|
861
|
-
]
|
|
862
|
-
};
|
|
863
|
-
});
|
|
864
|
-
}
|
|
865
|
-
|
|
866
|
-
// src/tools/templates.ts
|
|
867
|
-
import {
|
|
868
|
-
getTemplateById,
|
|
869
|
-
getTemplatesByCategory,
|
|
870
|
-
templates as templates2
|
|
871
|
-
} from "@secondlayer/subgraphs/templates";
|
|
872
|
-
import { z as z5 } from "zod/v4";
|
|
873
|
-
function registerTemplateTools(server) {
|
|
874
|
-
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")
|
|
876
|
-
}, async ({ category }) => {
|
|
877
|
-
const list = category ? getTemplatesByCategory(category) : templates2;
|
|
878
|
-
return {
|
|
879
|
-
content: [
|
|
880
|
-
{
|
|
881
|
-
type: "text",
|
|
882
|
-
text: JSON.stringify(list.map((t) => ({
|
|
883
|
-
id: t.id,
|
|
884
|
-
name: t.name,
|
|
885
|
-
description: t.description,
|
|
886
|
-
category: t.category
|
|
887
|
-
})), null, 2)
|
|
888
|
-
}
|
|
889
|
-
]
|
|
890
|
-
};
|
|
543
|
+
return { content: [{ type: "text", text: code }] };
|
|
891
544
|
});
|
|
892
|
-
defineTool(server, "
|
|
893
|
-
|
|
894
|
-
|
|
545
|
+
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.", {
|
|
546
|
+
code: z3.string().describe("TypeScript source code containing a defineWorkflow() call"),
|
|
547
|
+
expectedVersion: z3.string().regex(/^\d+\.\d+\.\d+$/).optional().describe("Stored version the client expects (major.minor.patch). Server returns 409 on mismatch."),
|
|
548
|
+
dryRun: z3.boolean().optional().describe("If true, validate and bundle only — do not persist.")
|
|
549
|
+
}, async ({ code, expectedVersion, dryRun }) => {
|
|
550
|
+
let bundled;
|
|
551
|
+
try {
|
|
552
|
+
bundled = await bundleWorkflowCode(code);
|
|
553
|
+
} catch (err) {
|
|
895
554
|
return {
|
|
555
|
+
isError: true,
|
|
896
556
|
content: [
|
|
897
557
|
{
|
|
898
558
|
type: "text",
|
|
899
|
-
text:
|
|
559
|
+
text: err instanceof Error ? err.message : String(err)
|
|
900
560
|
}
|
|
901
|
-
]
|
|
902
|
-
isError: true
|
|
561
|
+
]
|
|
903
562
|
};
|
|
904
563
|
}
|
|
564
|
+
const base = {
|
|
565
|
+
name: bundled.name,
|
|
566
|
+
trigger: bundled.trigger,
|
|
567
|
+
handlerCode: bundled.handlerCode,
|
|
568
|
+
sourceCode: bundled.sourceCode,
|
|
569
|
+
retries: bundled.retries,
|
|
570
|
+
timeout: bundled.timeout,
|
|
571
|
+
expectedVersion
|
|
572
|
+
};
|
|
573
|
+
try {
|
|
574
|
+
const result = dryRun ? await getClient().workflows.deploy({ ...base, dryRun: true }) : await getClient().workflows.deploy(base);
|
|
575
|
+
return {
|
|
576
|
+
content: [{ type: "text", text: JSON.stringify(result, null, 2) }]
|
|
577
|
+
};
|
|
578
|
+
} catch (err) {
|
|
579
|
+
if (err instanceof VersionConflictError) {
|
|
580
|
+
return {
|
|
581
|
+
isError: true,
|
|
582
|
+
content: [
|
|
583
|
+
{
|
|
584
|
+
type: "text",
|
|
585
|
+
text: JSON.stringify({
|
|
586
|
+
error: err.message,
|
|
587
|
+
code: "VERSION_CONFLICT",
|
|
588
|
+
currentVersion: err.currentVersion,
|
|
589
|
+
expectedVersion: err.expectedVersion
|
|
590
|
+
}, null, 2)
|
|
591
|
+
}
|
|
592
|
+
]
|
|
593
|
+
};
|
|
594
|
+
}
|
|
595
|
+
throw err;
|
|
596
|
+
}
|
|
597
|
+
});
|
|
598
|
+
defineTool(server, "workflows_runs", "List runs for a workflow. Optionally filter by status and limit results.", {
|
|
599
|
+
name: z3.string().describe("Workflow name"),
|
|
600
|
+
status: z3.enum(["running", "completed", "failed", "cancelled"]).optional().describe("Filter by run status"),
|
|
601
|
+
limit: z3.number().optional().describe("Max runs to return (default 20)")
|
|
602
|
+
}, async ({ name, status, limit }) => {
|
|
603
|
+
const { runs } = await getClient().workflows.listRuns(name, {
|
|
604
|
+
status,
|
|
605
|
+
limit
|
|
606
|
+
});
|
|
905
607
|
return {
|
|
906
608
|
content: [
|
|
907
609
|
{
|
|
908
610
|
type: "text",
|
|
909
|
-
text: JSON.stringify(
|
|
910
|
-
id: template.id,
|
|
911
|
-
name: template.name,
|
|
912
|
-
description: template.description,
|
|
913
|
-
category: template.category,
|
|
914
|
-
code: template.code,
|
|
915
|
-
prompt: template.prompt
|
|
916
|
-
}, null, 2)
|
|
611
|
+
text: JSON.stringify(runs, null, 2)
|
|
917
612
|
}
|
|
918
613
|
]
|
|
919
614
|
};
|
|
@@ -928,9 +623,7 @@ function createServer() {
|
|
|
928
623
|
name: "secondlayer",
|
|
929
624
|
version: pkg.version
|
|
930
625
|
});
|
|
931
|
-
registerTemplateTools(server);
|
|
932
626
|
registerScaffoldTools(server);
|
|
933
|
-
registerStreamTools(server);
|
|
934
627
|
registerSubgraphTools(server);
|
|
935
628
|
registerAccountTools(server);
|
|
936
629
|
registerWorkflowTools(server);
|
|
@@ -941,5 +634,5 @@ export {
|
|
|
941
634
|
createServer
|
|
942
635
|
};
|
|
943
636
|
|
|
944
|
-
//# debugId=
|
|
637
|
+
//# debugId=11774A508195F77F64756E2164756E21
|
|
945
638
|
//# sourceMappingURL=index.js.map
|