Skip to content

Commit 7cc068e

Browse files
chore(mcp): add line numbers to code tool errors
1 parent 9018b91 commit 7cc068e

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
@@ -130,6 +130,25 @@ function makeSdkProxy<T extends object>(obj: T, { path, isBelievedBad = false }:
130130
return proxy;
131131
}
132132

133+
function parseError(code: string, error: unknown): string | undefined {
134+
if (!(error instanceof Error)) return;
135+
const message = error.name ? `${error.name}: ${error.message}` : error.message;
136+
try {
137+
// Deno uses V8; the first "<anonymous>:LINE:COLUMN" is the top of stack.
138+
const lineNumber = error.stack?.match(/<anonymous>:([0-9]+):[0-9]+/)?.[1];
139+
// -1 for the zero-based indexing
140+
const line =
141+
lineNumber &&
142+
code
143+
.split('\n')
144+
.at(parseInt(lineNumber, 10) - 1)
145+
?.trim();
146+
return line ? `${message}\n at line ${lineNumber}\n ${line}` : message;
147+
} catch {
148+
return message;
149+
}
150+
}
151+
133152
const fetch = async (req: Request): Promise<Response> => {
134153
const { opts, code } = (await req.json()) as WorkerInput;
135154
if (code == null) {
@@ -169,21 +188,17 @@ const fetch = async (req: Request): Promise<Response> => {
169188
};
170189
try {
171190
let run_ = async (client: any) => {};
172-
eval(`
173-
${code}
174-
run_ = run;
175-
`);
191+
eval(`${code}\nrun_ = run;`);
176192
const result = await run_(makeSdkProxy(client, { path: ['client'] }));
177193
return Response.json({
178194
result,
179195
logLines,
180196
errLines,
181197
} satisfies WorkerSuccess);
182198
} catch (e) {
183-
const message = e instanceof Error ? e.message : undefined;
184199
return Response.json(
185200
{
186-
message,
201+
message: parseError(code, e),
187202
} satisfies WorkerError,
188203
{ status: 400, statusText: 'Code execution error' },
189204
);

0 commit comments

Comments
 (0)