← Back to Dashboard
1. Server Initialization2. Defining Tool Schemas3. Tool Execution & Errors

Tool Execution & Errors

📚 Tools & Functions⏱ 8 min⭐ 70 XP⌨ Hands-on lab

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.tool(
  "read_file",
  "Reads a file",
  { path: z.string() },
  async ({ path }) => {
    try {
      const data = await fs.readFile(path, 'utf8');
      return { content: [{ type: "text", text: data }] };
    } catch (e) {
      // ✅ 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 XP

Invoke a tool with invalid inputs and verify the standard MCP isError: true payload.

1Call read_file with a nonexistent path and verify error handling.
lab-sandbox — simulated environment
INFINITY LAB SANDBOX v2.6 — simulated shell
Type the command for the current objective. Helpers: "hint", "solution", "clear".
$
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.