Skip to content

Commit a960524

Browse files
authored
feat: support structuredContent in UserError (#174)
1 parent b36b27c commit a960524

File tree

2 files changed

+56
-0
lines changed

2 files changed

+56
-0
lines changed

src/FastMCP.test.ts

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -431,6 +431,61 @@ test("handles UserError errors", async () => {
431431
});
432432
});
433433

434+
test("handles UserError errors with extras", async () => {
435+
await runWithTestServer({
436+
run: async ({ client }) => {
437+
// Should include structuredContent if extras is present
438+
expect(
439+
await client.callTool({
440+
arguments: { a: 1, b: 2 },
441+
name: "add_with_extras",
442+
}),
443+
).toEqual({
444+
content: [{ text: "Something went wrong", type: "text" }],
445+
isError: true,
446+
structuredContent: { foo: "bar", num: 42 },
447+
});
448+
449+
// Should NOT include structuredContent if extras is not present
450+
expect(
451+
await client.callTool({
452+
arguments: { a: 1, b: 2 },
453+
name: "add_without_extras",
454+
}),
455+
).toEqual({
456+
content: [{ text: "Something went wrong", type: "text" }],
457+
isError: true,
458+
});
459+
},
460+
server: async () => {
461+
const server = new FastMCP({
462+
name: "Test",
463+
version: "1.0.0",
464+
});
465+
466+
server.addTool({
467+
description: "Throws UserError with extras",
468+
execute: async () => {
469+
throw new UserError("Something went wrong", { foo: "bar", num: 42 });
470+
},
471+
name: "add_with_extras",
472+
parameters: z.object({ a: z.number(), b: z.number() }),
473+
});
474+
475+
server.addTool({
476+
description: "Throws UserError without extras",
477+
execute: async () => {
478+
throw new UserError("Something went wrong");
479+
},
480+
name: "add_without_extras",
481+
parameters: z.object({ a: z.number(), b: z.number() }),
482+
});
483+
484+
return server;
485+
},
486+
});
487+
});
488+
434489
test("calling an unknown tool throws McpError with MethodNotFound code", async () => {
435490
await runWithTestServer({
436491
run: async ({ client }) => {

src/FastMCP.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1844,6 +1844,7 @@ export class FastMCPSession<
18441844
return {
18451845
content: [{ text: error.message, type: "text" }],
18461846
isError: true,
1847+
...(error.extras ? { structuredContent: error.extras } : {}),
18471848
};
18481849
}
18491850

0 commit comments

Comments
 (0)