diff --git a/src/server/index.test.ts b/src/server/index.test.ts index 6c63f25..978b26b 100644 --- a/src/server/index.test.ts +++ b/src/server/index.test.ts @@ -860,16 +860,70 @@ describe("Server.tool", () => { server.connect(serverTransport), ]); + const result = await client.request( + { + method: "tools/call", + params: { + name: "error-test", + }, + }, + CallToolResultSchema, + ); + + expect(result.isError).toBe(true); + expect(result.content).toEqual([ + { + type: "text", + text: "Tool execution failed", + }, + ]); + }); + + test("should throw McpError for invalid tool name", async () => { + const server = new Server({ + name: "test server", + version: "1.0", + }); + + const client = new Client( + { + name: "test client", + version: "1.0", + }, + { + capabilities: { + tools: {}, + }, + }, + ); + + server.tool("test-tool", async () => ({ + content: [ + { + type: "text", + text: "Test response", + }, + ], + })); + + const [clientTransport, serverTransport] = + InMemoryTransport.createLinkedPair(); + + await Promise.all([ + client.connect(clientTransport), + server.connect(serverTransport), + ]); + await expect( client.request( { method: "tools/call", params: { - name: "error-test", + name: "nonexistent-tool", }, }, CallToolResultSchema, ), - ).rejects.toThrow("Tool execution failed"); + ).rejects.toThrow(/Tool nonexistent-tool not found/); }); }); diff --git a/src/server/index.ts b/src/server/index.ts index db5e36a..469a3a7 100644 --- a/src/server/index.ts +++ b/src/server/index.ts @@ -405,10 +405,34 @@ export class Server< const args = parseResult.data; const cb = tool.callback as ToolCallback; - return await Promise.resolve(cb(args, extra)); + try { + return await Promise.resolve(cb(args, extra)); + } catch (error) { + return { + content: [ + { + type: "text", + text: error instanceof Error ? error.message : String(error), + }, + ], + isError: true, + }; + } } else { const cb = tool.callback as ToolCallback; - return await Promise.resolve(cb(extra)); + try { + return await Promise.resolve(cb(extra)); + } catch (error) { + return { + content: [ + { + type: "text", + text: error instanceof Error ? error.message : String(error), + }, + ], + isError: true, + }; + } } }, );