Skip to content

Commit c9f699c

Browse files
chore(mcp): add line numbers to code tool errors
1 parent 0b2ad3f commit c9f699c

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
@@ -163,6 +163,25 @@ function makeSdkProxy<T extends object>(obj: T, { path, isBelievedBad = false }:
163163
return proxy;
164164
}
165165

166+
function parseError(code: string, error: unknown): string | undefined {
167+
if (!(error instanceof Error)) return;
168+
const message = error.name ? `${error.name}: ${error.message}` : error.message;
169+
try {
170+
// Deno uses V8; the first "<anonymous>:LINE:COLUMN" is the top of stack.
171+
const lineNumber = error.stack?.match(/<anonymous>:([0-9]+):[0-9]+/)?.[1];
172+
// -1 for the zero-based indexing
173+
const line =
174+
lineNumber &&
175+
code
176+
.split('\n')
177+
.at(parseInt(lineNumber, 10) - 1)
178+
?.trim();
179+
return line ? `${message}\n at line ${lineNumber}\n ${line}` : message;
180+
} catch {
181+
return message;
182+
}
183+
}
184+
166185
const fetch = async (req: Request): Promise<Response> => {
167186
const { opts, code } = (await req.json()) as WorkerInput;
168187
if (code == null) {
@@ -202,21 +221,17 @@ const fetch = async (req: Request): Promise<Response> => {
202221
};
203222
try {
204223
let run_ = async (client: any) => {};
205-
eval(`
206-
${code}
207-
run_ = run;
208-
`);
224+
eval(`${code}\nrun_ = run;`);
209225
const result = await run_(makeSdkProxy(client, { path: ['client'] }));
210226
return Response.json({
211227
result,
212228
logLines,
213229
errLines,
214230
} satisfies WorkerSuccess);
215231
} catch (e) {
216-
const message = e instanceof Error ? e.message : undefined;
217232
return Response.json(
218233
{
219-
message,
234+
message: parseError(code, e),
220235
} satisfies WorkerError,
221236
{ status: 400, statusText: 'Code execution error' },
222237
);

0 commit comments

Comments
 (0)