Skip to content

Commit 25e4e59

Browse files
chore(mcp): add line numbers to code tool errors
1 parent 636829d commit 25e4e59

File tree

1 file changed

+21
-6
lines changed

1 file changed

+21
-6
lines changed

packages/mcp-server/src/code-tool-worker.ts

Lines changed: 21 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -160,6 +160,25 @@ function makeSdkProxy<T extends object>(obj: T, { path, isBelievedBad = false }:
160160
return proxy;
161161
}
162162

163+
function parseError(code: string, error: unknown): string | undefined {
164+
if (!(error instanceof Error)) return;
165+
const message = error.name ? `${error.name}: ${error.message}` : error.message;
166+
try {
167+
// Deno uses V8; the first "<anonymous>:LINE:COLUMN" is the top of stack.
168+
const lineNumber = error.stack?.match(/<anonymous>:([0-9]+):[0-9]+/)?.[1];
169+
// -1 for the zero-based indexing
170+
const line =
171+
lineNumber &&
172+
code
173+
.split('\n')
174+
.at(parseInt(lineNumber, 10) - 1)
175+
?.trim();
176+
return line ? `${message}\n at line ${lineNumber}\n ${line}` : message;
177+
} catch {
178+
return message;
179+
}
180+
}
181+
163182
const fetch = async (req: Request): Promise<Response> => {
164183
const { opts, code } = (await req.json()) as WorkerInput;
165184
if (code == null) {
@@ -199,21 +218,17 @@ const fetch = async (req: Request): Promise<Response> => {
199218
};
200219
try {
201220
let run_ = async (client: any) => {};
202-
eval(`
203-
${code}
204-
run_ = run;
205-
`);
221+
eval(`${code}\nrun_ = run;`);
206222
const result = await run_(makeSdkProxy(client, { path: ['client'] }));
207223
return Response.json({
208224
result,
209225
logLines,
210226
errLines,
211227
} satisfies WorkerSuccess);
212228
} catch (e) {
213-
const message = e instanceof Error ? e.message : undefined;
214229
return Response.json(
215230
{
216-
message,
231+
message: parseError(code, e),
217232
} satisfies WorkerError,
218233
{ status: 400, statusText: 'Code execution error' },
219234
);

0 commit comments

Comments
 (0)