Skip to content

Commit 70bf6d0

Browse files
chore(mcp): add line numbers to code tool errors
1 parent 3341c0e commit 70bf6d0

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
@@ -183,6 +183,25 @@ function makeSdkProxy<T extends object>(obj: T, { path, isBelievedBad = false }:
183183
return proxy;
184184
}
185185

186+
function parseError(code: string, error: unknown): string | undefined {
187+
if (!(error instanceof Error)) return;
188+
const message = error.name ? `${error.name}: ${error.message}` : error.message;
189+
try {
190+
// Deno uses V8; the first "<anonymous>:LINE:COLUMN" is the top of stack.
191+
const lineNumber = error.stack?.match(/<anonymous>:([0-9]+):[0-9]+/)?.[1];
192+
// -1 for the zero-based indexing
193+
const line =
194+
lineNumber &&
195+
code
196+
.split('\n')
197+
.at(parseInt(lineNumber, 10) - 1)
198+
?.trim();
199+
return line ? `${message}\n at line ${lineNumber}\n ${line}` : message;
200+
} catch {
201+
return message;
202+
}
203+
}
204+
186205
const fetch = async (req: Request): Promise<Response> => {
187206
const { opts, code } = (await req.json()) as WorkerInput;
188207
if (code == null) {
@@ -222,21 +241,17 @@ const fetch = async (req: Request): Promise<Response> => {
222241
};
223242
try {
224243
let run_ = async (client: any) => {};
225-
eval(`
226-
${code}
227-
run_ = run;
228-
`);
244+
eval(`${code}\nrun_ = run;`);
229245
const result = await run_(makeSdkProxy(client, { path: ['client'] }));
230246
return Response.json({
231247
result,
232248
logLines,
233249
errLines,
234250
} satisfies WorkerSuccess);
235251
} catch (e) {
236-
const message = e instanceof Error ? e.message : undefined;
237252
return Response.json(
238253
{
239-
message,
254+
message: parseError(code, e),
240255
} satisfies WorkerError,
241256
{ status: 400, statusText: 'Code execution error' },
242257
);

0 commit comments

Comments
 (0)