Tool Execution & Errors — Tools & Functions
← Back to Dashboard
1. Server Initialization2. Defining Tool Schemas3. Tool Execution & Errors
Tool Execution & Errors
Handling Tool Errors Gracefully
When an LLM provides bad arguments or an API call fails, your tool shouldn't crash the server. It should return a graceful error message back to the LLM so the AI can debug itself and try again.
server.registerTool(
"read_file",
{
description: "Reads a UTF-8 file from disk",
inputSchema: z.object({ path: z.string().describe("Target file path") })
},
async ({ path }) => {
try {
const data = await fs.readFile(path, 'utf8');
return { content: [{ type: "text", text: data }] };
} catch (e: any) {
// ✅ Allow the LLM to learn and retry:
return {
isError: true,
content: [{ type: "text", text: `Error reading file. Did you use the correct path? ${e.message}`}]
};
}
}
);
💡 Key Insight: The
isError: true flag tells the Host application to render the result as an error boundary, while feeding the error text back to the LLM for correction.⌨ HANDS-ON LABSimulate & Catch Tool Execution Error
⭐ +150 XPInvoke a tool with invalid inputs and verify the standard MCP isError: true payload.
1Call read_file with a nonexistent path and verify error handling.
OBJECTIVE 1 / 1 — type "hint" if stuck
🧪 Knowledge Check
Press 1-4 to select1 of 3
What is the best practice for handling errors inside a Tool execution?
Throw a fatal exception and crash.
Return an empty string.
Return the error details with the `isError: true` flag so the LLM can try again.
Exit the process immediately.