Error Handling Conventions
Throwing structured McpToolError instances, centralizing redaction via sanitizeMcpError, and maintaining the dual-audience copy contract.
Structured McpToolError class
Domain tools signal expected validation, permission, tier, or governance failures by throwing McpToolError from mcp/src/security/errors.ts. Each error carries a stable machine-readable code from the canonical 12-code taxonomy plus a plain server-owner message.
import { McpToolError } from '../security/errors.js';
if (tier === 'free') {
throw new McpToolError(
'TIER_UPGRADE_REQUIRED',
'AI Moderation requires a Pro or Enterprise plan on this server.',
{
requiredTier: 'pro',
currentTier: 'free',
upgradeUrl: `https://taicket.xyz/dashboard/${guildId}/premium`,
}
);
}Dual-audience message standard
AI clients surface tool error messages directly inside user chat threads. The code field exists for programmatic client handling and developer debugging; the message field is written strictly for Discord server owners with zero developer terminology.
| Avoid in message | Write instead |
|---|---|
| Mongoose E11000 duplicate key on panelconfigs.panelId | A ticket panel with that name already exists in this server. |
| ZodError: invalid_string at guildId expected regex /^\d{17,20}$/ | Please choose a valid Discord server before continuing. |
| RBAC checkRealAdminGuild failed: caller lacks 0x8 or 0x20 | Only a full Discord server administrator or the server owner can change server settings. |
| HTTP 403 Discord API 50013 Missing Permissions on channel 123 | Taicket does not have permission to post messages in the selected channel. |
Centralized interception with sanitizeMcpError
The top-level MCP tool dispatcher wraps every handler in try/catch and funnels all thrown values through sanitizeMcpError(err, requestId). Known McpToolError instances preserve their code and safe metadata; ZodError instances map to VALIDATION_ERROR with field paths; Discord REST errors map cleanly to DISCORD_API_ERROR or CROSS_GUILD_RESOURCE; all other errors collapse to INTERNAL_ERROR.
try {
const result = await tool.execute(parsedInput, ctx);
return formatToolSuccess(result);
} catch (error) {
const safeError = sanitizeMcpError(error, requestId);
logger.warn(
{ requestId, toolName: tool.name, errorCode: safeError.code },
'MCP tool call returned error'
);
return formatToolError(safeError);
}