Back to course

Handling Tool Errors Gracefully

Model Context Protocol (MCP) Server Engineering

Error Handling

What happens if the file doesn't exist? Your server shouldn't crash. MCP handles errors by returning a special response or throwing a standard error.

Best Practice

Wrap your logic in a try...catch block.

typescript } catch (error) { return { content: [{ type: "text", text: Error: ${error.message} }], isError: true }; }

Assignment: Modify your File Reader tool to handle ENOENT (file not found) errors and return a helpful message to the AI.