Introduction
Building MCP servers in production means planning for failure before it happens. Network timeouts, malformed client requests, authentication failures, and tool execution errors are inevitable. How your server handles these situations determines whether users experience a graceful degradation or a confusing crash. This post shares practical error handling patterns I've found useful when developing MCP servers, along with concrete examples you can adapt to your own implementations.
For additional context on MCP error handling standards, refer to the official MCP specification which defines the JSON-RPC error response format and standard error codes.
Common MCP Error Scenarios
MCP servers using JSON-RPC transports encounter several recurring error categories:
Transport errors: Connection drops, TLS handshake failures, and HTTP 429 rate limiting responses interrupt the client-server channel before any tool logic runs. These errors often manifest as connection resets, timeout exceptions, or incomplete JSON-RPC messages that cannot be parsed.
Authentication errors: Missing or expired bearer tokens, invalid signatures, and revoked credentials prevent clients from accessing protected capabilities. These errors should be returned promptly with clear guidance on how clients can re-authenticate.
Validation errors: Clients send malformed JSON-RPC requests, missing required parameters, or parameters with wrong types. MCP tool schemas define expected input, and invalid inputs should be rejected before reaching business logic.
Tool execution errors: Even well-formed requests can fail at runtime — files don't exist, external APIs are unreachable, database queries time out, or permissions are insufficient. These errors require careful handling to distinguish transient failures from permanent ones.
Error Response Design
MCP uses JSON-RPC 2.0 error responses with standardized error codes. Key design principles:
-
Use standard JSON-RPC error codes where applicable: -32700 for parse errors, -32600 for invalid requests, -32601 for method not found, -32602 for invalid params, and -32603 for internal errors.
-
Add MCP-specific error codes in the -32000 to -32099 range for domain-specific failures such as authentication failures, authorization denials, and tool-specific errors.
-
Include actionable error messages that tell clients what went wrong and how to fix it. Instead of "Internal server error," use "File not found at path /data/config.json — check that the path exists and the service account has read permission."
-
Never expose stack traces or internal system details to clients. Log them server-side for debugging, but return sanitized messages to the client.
Implementation Example: Structured Error Handling
Here's a TypeScript pattern for structured error handling in an MCP server:
class MCPError extends Error {
constructor(public code: number, message: string, public data?: unknown) {
super(message);
this.name = 'MCPError';
}
}
async function handleToolCall(toolName: string, args: unknown, clientId: string, requestId: string) {
try {
validateInput(toolName, args);
const result = await executeTool(toolName, args, clientId);
return { jsonrpc: '2.0', id: requestId, result };
} catch (error) {
if (error instanceof MCPError) {
return { jsonrpc: '2.0', id: requestId, error: { code: error.code, message: error.message, data: error.data } };
}
logError(error, clientId, toolName, args);
return { jsonrpc: '2.0', id: requestId, error: { code: -32603, message: 'Internal server error' } };
}
}
Authentication and Authorization Error Patterns
Authentication failures deserve special attention because they're often the first interaction a client has with your server:
const AUTH_ERROR_CODES = {
MISSING_TOKEN: -32001,
INVALID_TOKEN: -32002,
EXPIRED_TOKEN: -32003,
INSUFFICIENT_SCOPE: -32004,
} as const;
function validateAuthentication(authHeader: string | undefined): string {
if (!authHeader?.startsWith('Bearer ')) {
throw new MCPError(AUTH_ERROR_CODES.MISSING_TOKEN, 'Missing or invalid Authorization header. Expected: Bearer <token>');
}
const token = authHeader.slice(7);
if (!verifyToken(token)) {
throw new MCPError(AUTH_ERROR_CODES.INVALID_TOKEN, 'Invalid or expired authentication token');
}
return token;
}
function authorizeTool(token: string, toolName: string): void {
const claims = decodeToken(token);
const requiredScope = TOOL_SCOPES[toolName];
if (requiredScope && !claims.scopes.includes(requiredScope)) {
throw new MCPError(AUTH_ERROR_CODES.INSUFFICIENT_SCOPE, `Tool '${toolName}' requires scope '${requiredScope}'`);
}
}
Validation Error Handling
Validate inputs at the boundary before any business logic runs:
function validateInput(toolName: string, args: unknown): void {
const schema = TOOL_SCHEMAS[toolName];
if (!schema) {
throw new MCPError(-32601, `Unknown tool: ${toolName}`);
}
const result = schema.safeParse(args);
if (!result.success) {
const details = result.error.errors.map(e => `${e.path.join('.')}: ${e.message}`).join('; ');
throw new MCPError(-32602, `Invalid parameters for tool '${toolName}': ${details}`);
}
}
Tool Execution Error Patterns
Distinguish between transient and permanent failures:
async function executeTool(toolName: string, args: unknown, clientId: string): Promise<unknown> {
try {
return await TOOL_HANDLERS[toolName](args, clientId);
} catch (error) {
if (error instanceof FileNotFoundError) {
throw new MCPError(-32010, `Resource not found: ${error.path}`, { path: error.path });
}
if (error instanceof ExternalAPIError) {
if (error.isRetryable) {
throw new MCPError(-32011, 'External service temporarily unavailable. Please retry.', { retryAfter: error.retryAfter });
}
throw new MCPError(-32012, `External service error: ${error.message}`);
}
if (error instanceof PermissionError) {
throw new MCPError(-32013, `Permission denied: ${error.resource}`, { resource: error.resource });
}
throw error;
}
}
Logging and Observability
Every error should be logged with context: client identifier, tool name, request parameters (sanitized), error code, and timestamp. Structured JSON logs make it easy to query error patterns and correlate related failures:
function logError(error: Error, clientId: string, toolName: string, args: unknown) {
const logEntry = {
timestamp: new Date().toISOString(),
level: 'error',
clientId: hashClientId(clientId),
toolName,
args: sanitizeArgs(args),
error: {
name: error.name,
message: error.message,
code: error instanceof MCPError ? error.code : -32603,
},
stack: process.env.NODE_ENV === 'development' ? error.stack : undefined,
};
logger.error(JSON.stringify(logEntry));
}
Track error rates by client and by tool to identify problematic clients or flaky tools before users report them. Set up alerts for error rate spikes exceeding baseline by more than 50%.
Client-Side Error Handling Guidance
Provide documentation for MCP clients on how to handle your server's error responses:
- Retry logic: Transient errors (rate limits, temporary external failures) should trigger exponential backoff with jitter.
- Re-authentication: Authentication errors (401 equivalents) should trigger token refresh flows.
- User-facing messages: Validation errors should be surfaced directly to users when they result from user input.
- Graceful degradation: When optional tools fail, the client should continue with available capabilities.
Testing Error Scenarios
Include error scenarios in your test suite:
describe('MCP error handling', () => {
it('returns structured error for missing authentication', async () => {
const response = await callTool('read_file', { path: '/etc/passwd' }, undefined);
expect(response.error.code).toBe(AUTH_ERROR_CODES.MISSING_TOKEN);
});
it('returns validation error for missing required parameter', async () => {
const response = await callTool('read_file', {}, validToken);
expect(response.error.code).toBe(-32602);
expect(response.error.message).toContain('path');
});
it('returns not found error for missing file', async () => {
const response = await callTool('read_file', { path: '/nonexistent.txt' }, validToken);
expect(response.error.code).toBe(-32010);
});
});
Conclusion
Effective MCP error handling combines standard JSON-RPC patterns with MCP-specific considerations. Use standard error codes where possible, add domain-specific codes for MCP scenarios, return actionable messages to clients, and log everything server-side. Start with the basics — validate inputs, handle authentication failures gracefully, and log all errors — then refine based on real-world usage patterns.
For related guidance on building secure MCP servers, see Practical Guide to Building MCP Servers with Secure Authentication in 2026.