Error Handling
Error Handling in MCP
Robust error handling makes your MCP server reliable and helps the AI recover gracefully.
typescript
// Good error handling pattern
server.tool("risky_operation", "...", schema, async (params) => {
try {
const result = await performOperation(params);
return { content: [{ type: "text", text: result }] };
} catch (error) {
console.error("Operation failed:", error);
return {
isError: true,
content: [{
type: "text",
text: `Operation failed: ${error.message}. Please check the parameters and try again.`,
}],
};
}
});PreviewTypeScriptRead Only
Copy this code and run it locally with
npx tsx server.ts