Skip to content

Commit 48cfd3a

Browse files
chore(mcp): add line numbers to code tool errors
1 parent 69bd7b0 commit 48cfd3a

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

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

0 commit comments

Comments
 (0)