Skip to content

Commit e9eb036

Browse files
chore(mcp): add line numbers to code tool errors
1 parent a2c4ebe commit e9eb036

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

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

0 commit comments

Comments
 (0)