Skip to content

Commit b3c083e

Browse files
chore(mcp): add line numbers to code tool errors
1 parent 92613e9 commit b3c083e

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
@@ -121,6 +121,25 @@ function makeSdkProxy<T extends object>(obj: T, { path, isBelievedBad = false }:
121121
return proxy;
122122
}
123123

124+
function parseError(code: string, error: unknown): string | undefined {
125+
if (!(error instanceof Error)) return;
126+
const message = error.name ? `${error.name}: ${error.message}` : error.message;
127+
try {
128+
// Deno uses V8; the first "<anonymous>:LINE:COLUMN" is the top of stack.
129+
const lineNumber = error.stack?.match(/<anonymous>:([0-9]+):[0-9]+/)?.[1];
130+
// -1 for the zero-based indexing
131+
const line =
132+
lineNumber &&
133+
code
134+
.split('\n')
135+
.at(parseInt(lineNumber, 10) - 1)
136+
?.trim();
137+
return line ? `${message}\n at line ${lineNumber}\n ${line}` : message;
138+
} catch {
139+
return message;
140+
}
141+
}
142+
124143
const fetch = async (req: Request): Promise<Response> => {
125144
const { opts, code } = (await req.json()) as WorkerInput;
126145
if (code == null) {
@@ -160,21 +179,17 @@ const fetch = async (req: Request): Promise<Response> => {
160179
};
161180
try {
162181
let run_ = async (client: any) => {};
163-
eval(`
164-
${code}
165-
run_ = run;
166-
`);
182+
eval(`${code}\nrun_ = run;`);
167183
const result = await run_(makeSdkProxy(client, { path: ['client'] }));
168184
return Response.json({
169185
result,
170186
logLines,
171187
errLines,
172188
} satisfies WorkerSuccess);
173189
} catch (e) {
174-
const message = e instanceof Error ? e.message : undefined;
175190
return Response.json(
176191
{
177-
message,
192+
message: parseError(code, e),
178193
} satisfies WorkerError,
179194
{ status: 400, statusText: 'Code execution error' },
180195
);

0 commit comments

Comments
 (0)