-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathruns.ts
More file actions
340 lines (285 loc) · 10.3 KB
/
runs.ts
File metadata and controls
340 lines (285 loc) · 10.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
import { AnyRunShape } from "@trigger.dev/core/v3";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { toolsMetadata } from "../config.js";
import { formatRun, formatRunList, formatRunShape, formatRunTrace } from "../formatters.js";
import { CommonRunsInput, GetRunDetailsInput, ListRunsInput, WaitForRunInput } from "../schemas.js";
import { respondWithError, toolHandler } from "../utils.js";
// Cache formatted traces in temp files keyed by runId.
// Each entry stores the file path and total line count.
const traceCache = new Map<string, { filePath: string; totalLines: number; expiresAt: number }>();
const TRACE_CACHE_TTL_MS = 10 * 60 * 1000; // 10 minutes
function getTraceCacheDir(): string {
const dir = path.join(os.tmpdir(), "trigger-mcp-traces");
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, { recursive: true });
}
return dir;
}
/** Read a page of lines from a file. Returns the lines and whether there are more. */
function readLinesPage(
filePath: string,
offset: number,
limit: number,
totalLines: number
): { lines: string[]; hasMore: boolean; nextCursor: string | null } {
const content = fs.readFileSync(filePath, "utf-8");
const allLines = content.split("\n");
const pageLines = allLines.slice(offset, offset + limit);
const end = offset + limit;
const hasMore = end < totalLines;
return {
lines: pageLines,
hasMore,
nextCursor: hasMore ? String(end) : null,
};
}
export const getRunDetailsTool = {
name: toolsMetadata.get_run_details.name,
title: toolsMetadata.get_run_details.title,
description: toolsMetadata.get_run_details.description,
inputSchema: GetRunDetailsInput.shape,
handler: toolHandler(GetRunDetailsInput.shape, async (input, { ctx }) => {
ctx.logger?.log("calling get_run_details", { input });
if (ctx.options.devOnly && input.environment !== "dev") {
return respondWithError(
`This MCP server is only available for the dev environment. You tried to access the ${input.environment} environment. Remove the --dev-only flag to access other environments.`
);
}
const projectRef = await ctx.getProjectRef({
projectRef: input.projectRef,
cwd: input.configPath,
});
const apiClient = await ctx.getApiClient({
projectRef,
environment: input.environment,
scopes: [`read:runs:${input.runId}`],
branch: input.branch,
});
const limit = input.maxTraceLines;
const offset = input.cursor ? parseInt(input.cursor, 10) : 0;
// Check if we have a cached trace file for this run
let cached = traceCache.get(input.runId);
if (cached && Date.now() >= cached.expiresAt) {
// Expired — clean up
try {
fs.unlinkSync(cached.filePath);
} catch {}
traceCache.delete(input.runId);
cached = undefined;
}
let formattedRun: string | undefined;
let runUrl: string | undefined;
if (!cached) {
// Fetch and cache the full trace
const [runResult, traceResult] = await Promise.all([
apiClient.retrieveRun(input.runId),
apiClient.retrieveRunTrace(input.runId),
]);
formattedRun = formatRun(runResult);
runUrl = await ctx.getDashboardUrl(`/projects/v3/${projectRef}/runs/${runResult.id}`);
// Format the full trace (no line limit — we're writing to a file)
const fullTrace = formatRunTrace(traceResult.trace, Infinity);
const traceLines = fullTrace.split("\n");
// Write to temp file
const filePath = path.join(getTraceCacheDir(), `${input.runId}.txt`);
fs.writeFileSync(filePath, fullTrace, "utf-8");
// Only cache runs in terminal states — active runs need fresh traces
const terminalStatuses = new Set([
"COMPLETED",
"CANCELED",
"FAILED",
"CRASHED",
"SYSTEM_FAILURE",
"EXPIRED",
"TIMED_OUT",
]);
cached = {
filePath,
totalLines: traceLines.length,
expiresAt: Date.now() + TRACE_CACHE_TTL_MS,
};
if (terminalStatuses.has(runResult.status)) {
traceCache.set(input.runId, cached);
}
}
// Read the requested page
const page = readLinesPage(cached.filePath, offset, limit, cached.totalLines);
const content: string[] = [];
// Only include run details on the first page
if (offset === 0) {
if (!formattedRun) {
// Cursor pagination — fetch run details for context
const runResult = await apiClient.retrieveRun(input.runId);
formattedRun = formatRun(runResult);
runUrl = await ctx.getDashboardUrl(`/projects/v3/${projectRef}/runs/${runResult.id}`);
}
content.push("## Run Details");
content.push(formattedRun);
content.push("");
}
content.push(
`## Run Trace (lines ${offset + 1}-${offset + page.lines.length} of ${cached.totalLines})`
);
content.push(page.lines.join("\n"));
if (page.hasMore) {
content.push("");
content.push(
`**More trace available.** Call \`get_run_details\` again with \`cursor: "${page.nextCursor}"\` and \`runId: "${input.runId}"\` to see the next page.`
);
}
if (runUrl && offset === 0) {
content.push("");
content.push(`[View in dashboard](${runUrl})`);
}
return {
content: [
{
type: "text",
text: content.join("\n"),
},
],
};
}),
};
export const waitForRunToCompleteTool = {
name: toolsMetadata.wait_for_run_to_complete.name,
title: toolsMetadata.wait_for_run_to_complete.title,
description: toolsMetadata.wait_for_run_to_complete.description,
inputSchema: WaitForRunInput.shape,
handler: toolHandler(WaitForRunInput.shape, async (input, { ctx, signal }) => {
ctx.logger?.log("calling wait_for_run_to_complete", { input });
if (ctx.options.devOnly && input.environment !== "dev") {
return respondWithError(
`This MCP server is only available for the dev environment. You tried to access the ${input.environment} environment. Remove the --dev-only flag to access other environments.`
);
}
const projectRef = await ctx.getProjectRef({
projectRef: input.projectRef,
cwd: input.configPath,
});
const apiClient = await ctx.getApiClient({
projectRef,
environment: input.environment,
scopes: [`read:runs:${input.runId}`],
branch: input.branch,
});
const timeoutMs = input.timeoutInSeconds * 1000;
const timeoutSignal = AbortSignal.timeout(timeoutMs);
const combinedSignal = signal
? AbortSignal.any([signal, timeoutSignal])
: timeoutSignal;
const runSubscription = apiClient.subscribeToRun(input.runId, { signal: combinedSignal });
const readableStream = runSubscription.getReader();
let run: AnyRunShape | null = null;
let timedOut = false;
try {
while (true) {
const { done, value } = await readableStream.read();
if (done) {
break;
}
run = value;
if (value.isCompleted) {
break;
}
}
} catch (error) {
if (timeoutSignal.aborted) {
timedOut = true;
} else {
throw error;
}
}
if (!run) {
return respondWithError("Run not found");
}
const prefix = timedOut
? `Timed out after ${input.timeoutInSeconds}s. Returning current run state:\n\n`
: "";
return {
content: [{ type: "text", text: prefix + formatRunShape(run) }],
};
}),
};
export const cancelRunTool = {
name: toolsMetadata.cancel_run.name,
title: toolsMetadata.cancel_run.title,
description: toolsMetadata.cancel_run.description,
inputSchema: CommonRunsInput.shape,
handler: toolHandler(CommonRunsInput.shape, async (input, { ctx }) => {
ctx.logger?.log("calling cancel_run", { input });
if (ctx.options.devOnly && input.environment !== "dev") {
return respondWithError(
`This MCP server is only available for the dev environment. You tried to access the ${input.environment} environment. Remove the --dev-only flag to access other environments.`
);
}
const projectRef = await ctx.getProjectRef({
projectRef: input.projectRef,
cwd: input.configPath,
});
const apiClient = await ctx.getApiClient({
projectRef,
environment: input.environment,
scopes: [`write:runs:${input.runId}`, `read:runs:${input.runId}`],
branch: input.branch,
});
await apiClient.cancelRun(input.runId);
const retrieveResult = await apiClient.retrieveRun(input.runId);
const runUrl = await ctx.getDashboardUrl(
`/projects/v3/${projectRef}/runs/${retrieveResult.id}`
);
const content = [
`Run ${retrieveResult.id} canceled.`,
`Status: ${retrieveResult.status}`,
`Task: ${retrieveResult.taskIdentifier}`,
`[View in dashboard](${runUrl})`,
];
return {
content: [{ type: "text", text: content.join("\n") }],
};
}),
};
export const listRunsTool = {
name: toolsMetadata.list_runs.name,
title: toolsMetadata.list_runs.title,
description: toolsMetadata.list_runs.description,
inputSchema: ListRunsInput.shape,
handler: toolHandler(ListRunsInput.shape, async (input, { ctx }) => {
ctx.logger?.log("calling list_runs", { input });
if (ctx.options.devOnly && input.environment !== "dev") {
return respondWithError(
`This MCP server is only available for the dev environment. You tried to access the ${input.environment} environment. Remove the --dev-only flag to access other environments.`
);
}
const projectRef = await ctx.getProjectRef({
projectRef: input.projectRef,
cwd: input.configPath,
});
const apiClient = await ctx.getApiClient({
projectRef,
environment: input.environment,
scopes: ["read:runs"],
branch: input.branch,
});
const $from = typeof input.from === "string" ? new Date(input.from) : undefined;
const $to = typeof input.to === "string" ? new Date(input.to) : undefined;
const result = await apiClient.listRuns({
after: input.cursor,
limit: input.limit,
status: input.status,
taskIdentifier: input.taskIdentifier,
version: input.version,
tag: input.tag,
from: $from,
to: $to,
period: input.period,
machine: input.machine,
});
const formattedRuns = formatRunList(result);
return {
content: [{ type: "text", text: formattedRuns }],
};
}),
};