Handling Requests

Handling MCP Requests Properly

Learn how to handle errors, validate inputs, and return structured responses from your MCP server.
typescript
// Always validate and handle errors gracefully
server.tool("fetch_url", "Fetch content from a URL", {
  url: z.string().url().describe("URL to fetch"),
}, async ({ url }) => {
  try {
    const response = await fetch(url);
    if (!response.ok) {
      return {
        isError: true,
        content: [{ type: "text", text: `HTTP ${response.status}: ${response.statusText}` }],
      };
    }
    const text = await response.text();
    return { content: [{ type: "text", text: text.slice(0, 5000) }] };
  } catch (error) {
    return {
      isError: true,
      content: [{ type: "text", text: `Error: ${error.message}` }],
    };
  }
});

Tip:Always use isError: true for error responses. This tells the AI the operation failed so it can handle it appropriately.

PreviewTypeScriptRead Only
Copy this code and run it locally with npx tsx server.ts

💬 Got questions? Ask me anything!