Skip to content

Commit f251424

Browse files
chore(mcp): add line numbers to code tool errors
1 parent 41d7085 commit f251424

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
@@ -136,6 +136,25 @@ function makeSdkProxy<T extends object>(obj: T, { path, isBelievedBad = false }:
136136
return proxy;
137137
}
138138

139+
function parseError(code: string, error: unknown): string | undefined {
140+
if (!(error instanceof Error)) return;
141+
const message = error.name ? `${error.name}: ${error.message}` : error.message;
142+
try {
143+
// Deno uses V8; the first "<anonymous>:LINE:COLUMN" is the top of stack.
144+
const lineNumber = error.stack?.match(/<anonymous>:([0-9]+):[0-9]+/)?.[1];
145+
// -1 for the zero-based indexing
146+
const line =
147+
lineNumber &&
148+
code
149+
.split('\n')
150+
.at(parseInt(lineNumber, 10) - 1)
151+
?.trim();
152+
return line ? `${message}\n at line ${lineNumber}\n ${line}` : message;
153+
} catch {
154+
return message;
155+
}
156+
}
157+
139158
const fetch = async (req: Request): Promise<Response> => {
140159
const { opts, code } = (await req.json()) as WorkerInput;
141160
if (code == null) {
@@ -175,21 +194,17 @@ const fetch = async (req: Request): Promise<Response> => {
175194
};
176195
try {
177196
let run_ = async (client: any) => {};
178-
eval(`
179-
${code}
180-
run_ = run;
181-
`);
197+
eval(`${code}\nrun_ = run;`);
182198
const result = await run_(makeSdkProxy(client, { path: ['client'] }));
183199
return Response.json({
184200
result,
185201
logLines,
186202
errLines,
187203
} satisfies WorkerSuccess);
188204
} catch (e) {
189-
const message = e instanceof Error ? e.message : undefined;
190205
return Response.json(
191206
{
192-
message,
207+
message: parseError(code, e),
193208
} satisfies WorkerError,
194209
{ status: 400, statusText: 'Code execution error' },
195210
);

0 commit comments

Comments
 (0)