VOOZH about

URL: https://deepwiki.com/WordPress/mcp-adapter/6.1-error-handling

⇱ Error Handling | WordPress/mcp-adapter | DeepWiki


Loading...
Menu

Error Handling

This document describes the error handling architecture in the MCP Adapter system, including error formats, the McpErrorFactory utility, WP_Error integration, error handler implementations, and error propagation patterns.

For transport-level authentication and permission errors, see Transport Permissions. For observability and event tracking related to errors, see Observability. For ability-level permission checking, see Security and Permissions.

Overview

The MCP Adapter implements a comprehensive error handling system with three primary components:

  1. McpErrorFactory: Centralized factory for creating standardized JSON-RPC error responses
  2. Error Handler Interface: Pluggable logging and monitoring via McpErrorHandlerInterface
  3. Dual Error Formats: JSON-RPC 2.0 errors for protocol issues, isError format for tool execution problems

The system integrates WordPress WP_Error objects, provides detailed error metadata for observability, and ensures errors are properly logged, tracked, and communicated to MCP clients.

Sources: includes/Handlers/Tools/ToolsHandler.php1-447

Error Response Formats

The MCP Adapter uses two distinct error formats depending on the nature of the failure.

JSON-RPC 2.0 Errors (Protocol Errors)

Protocol-level errors use the JSON-RPC 2.0 error format and are returned for issues that prevent request processing:


Used for:

  • Missing or invalid parameters
  • Tool/resource/prompt not found
  • Internal errors (ability retrieval failed)
  • Invalid session

Sources: includes/Handlers/Tools/ToolsHandler.php102-110 includes/Handlers/Tools/ToolsHandler.php266-282

Tool Execution Errors (isError Format)

Per the MCP specification, errors originating from tool execution use the isError format:


Used for:

  • Permission denied (ability-level)
  • Permission check exceptions
  • WP_Error objects from ability execution
  • Execution exceptions

Sources: includes/Handlers/Tools/ToolsHandler.php142-158 includes/Handlers/Tools/ToolsHandler.php330-349

Error Format Decision Flow


Decision Logic:

Error StageConditionFormatfailure_reason
Parameter validationMissing required parameterJSON-RPCmissing_parameter
Component lookupTool/resource/prompt not foundJSON-RPCnot_found
Ability retrievalget_ability() returns WP_ErrorJSON-RPCability_retrieval_failed
Permission checkReturns false or WP_ErrorisErrorpermission_denied
Permission checkThrows exceptionisErrorpermission_check_failed
ExecutionReturns WP_ErrorisErrorwp_error
ExecutionThrows exceptionisErrorexecution_failed

Sources: includes/Handlers/Tools/ToolsHandler.php116-158 tests/Unit/Handlers/ToolsHandlerTest.php54-306

McpErrorFactory

The McpErrorFactory class provides static methods for creating standardized JSON-RPC error responses with proper error codes and messages.

Error Factory Methods


Usage Examples

Missing Parameter:


Tool Not Found:


Permission Denied:


Internal Error:


JSON-RPC Error Codes

MethodError CodeDescription
missing_parameter()-32602Invalid params - missing required parameter
tool_not_found()-32601Method not found - tool doesn't exist
permission_denied()-32000Server error - insufficient permissions
internal_error()-32603Internal error - unexpected server failure
invalid_params()-32602Invalid params - malformed request

Sources: includes/Handlers/Tools/ToolsHandler.php104 includes/Handlers/Tools/ToolsHandler.php275 includes/Handlers/Tools/ToolsHandler.php341 includes/Handlers/Tools/ToolsHandler.php201 includes/Handlers/Tools/ToolsHandler.php302 includes/Handlers/Tools/ToolsHandler.php360

WP_Error Integration

The system seamlessly integrates WordPress WP_Error objects at multiple stages of request processing.

WP_Error Handling Locations


WP_Error from get_ability()

When retrieving an ability fails (e.g., ability not registered), a WP_Error is returned and converted to a JSON-RPC error:


Sources: includes/Handlers/Tools/ToolsHandler.php289-310

WP_Error from Permission Check

When a permission callback returns a WP_Error, it's converted to an isError response with the error code used as the failure_reason:


Sources: includes/Handlers/Tools/ToolsHandler.php329-349

WP_Error from Execute Callback

When an ability's execute callback returns a WP_Error, it's converted to an isError format response:


Note: This error response is later converted by call_tool() from JSON-RPC format to isError format before being returned to the client.

Sources: includes/Handlers/Tools/ToolsHandler.php376-400

Example: Using WP_Error in Abilities


Sources: docs/getting-started/basic-examples.md82-84 tests/Unit/Handlers/ToolsHandlerTest.php112-158

Error Handler Interface

The McpErrorHandlerInterface defines the contract for error logging and monitoring implementations.

Interface Definition


Built-in Implementation: ErrorLogMcpErrorHandler

The default error handler logs to PHP's error log:


Usage in handlers:


Sources: includes/Handlers/Tools/ToolsHandler.php267-272 includes/Handlers/Tools/ToolsHandler.php192-198

Custom Error Handler Implementation

To implement custom error handling (e.g., Sentry, Datadog):


Register with server:


Sources: docs/troubleshooting/common-issues.md308-324

Test Fixture: DummyErrorHandler

For testing, the system provides a DummyErrorHandler that captures logged messages:


This allows test assertions like:


Sources: tests/Unit/Handlers/ToolsHandlerTest.php64-78

Error Propagation and Logging Flow

Errors flow through multiple layers with logging at strategic points.


Logging Points

1. Component Not Found:


2. Ability Retrieval Failed:


3. Permission Check Exception:


4. WP_Error from Execution:


5. Execution Exception:


6. Top-Level Exception:


Sources: includes/Handlers/Tools/ToolsHandler.php267-272 includes/Handlers/Tools/ToolsHandler.php293-299 includes/Handlers/Tools/ToolsHandler.php351-357 includes/Handlers/Tools/ToolsHandler.php377-384 includes/Handlers/Tools/ToolsHandler.php424-430 includes/Handlers/Tools/ToolsHandler.php192-198

Exception Handling Patterns

The system uses try-catch blocks at strategic points to handle unexpected exceptions gracefully.

Handler-Level Try-Catch

The top-level try-catch in call_tool() catches any unhandled exceptions:


Sources: includes/Handlers/Tools/ToolsHandler.php191-210

Permission Check Try-Catch

Permission callbacks are wrapped in try-catch to handle exceptions during authorization:


Sources: includes/Handlers/Tools/ToolsHandler.php328-369

Execution Try-Catch

Ability execution is wrapped to catch exceptions from the execute callback:


Sources: includes/Handlers/Tools/ToolsHandler.php372-445

Error Metadata

All error responses include a _metadata field that provides context for observability and debugging.

Metadata Structure


Common Metadata Fields

FieldTypeDescriptionExample
component_typestringType of MCP component'tool', 'resource', 'prompt'
tool_namestringName of the tool'my-plugin-create-post'
resource_uristringURI of the resource'wordpress://site/config'
prompt_namestringName of the prompt'code-review'
ability_namestringUnderlying ability name'my-plugin/create-post'
failure_reasonstringError classificationSee table below
error_codestringWordPress error code'insufficient_permissions'
error_typestringException class name'RuntimeException'

Failure Reason Values

failure_reasonMeaningError Format
missing_parameterRequired parameter not providedJSON-RPC
not_foundComponent doesn't existJSON-RPC
ability_retrieval_failedFailed to get underlying abilityJSON-RPC
permission_deniedAuthorization check failedisError
permission_check_failedException during permission checkisError
wp_errorAbility returned WP_ErrorisError
execution_failedException during executionisError
exceptionUnhandled exception at top levelJSON-RPC

Metadata Extraction by RequestRouter

The RequestRouter extracts _metadata from handler responses for observability before returning the clean response to clients:


This ensures clients never receive internal metadata while preserving observability data.

Sources: includes/Handlers/Tools/ToolsHandler.php105-109 includes/Handlers/Tools/ToolsHandler.php276-280 includes/Handlers/Tools/ToolsHandler.php303-309 includes/Handlers/Tools/ToolsHandler.php342-348 includes/Handlers/Tools/ToolsHandler.php392-398 includes/Handlers/Tools/ToolsHandler.php437-443

Error Handling in Abilities

Best practices for implementing error handling in ability callbacks.

Execute Callback Error Handling

Option 1: Return WP_Error (Recommended)


Option 2: Throw Exception


Option 3: Return Error Array (Legacy)

Some abilities return error information in array format. The handler supports both string and array error formats:


Sources: includes/Handlers/Tools/ToolsHandler.php137-141 tests/Unit/Handlers/ToolsHandlerTest.php384-426

Permission Callback Error Handling

Return false or WP_Error for denied access:


Avoid exceptions in permission callbacks - they are caught and converted to permission_check_failed errors, which is less specific than returning WP_Error with a proper error code.

Sources: includes/Handlers/Tools/ToolsHandler.php329-349 includes/Handlers/Tools/ToolsHandler.php350-369

Debugging Error Scenarios

Enable Debug Logging

Add to wp-config.php:


Monitor Error Log


Sources: docs/troubleshooting/common-issues.md248-254 docs/troubleshooting/common-issues.md272-282

Add Debug Logging to Abilities


Sources: docs/troubleshooting/common-issues.md218-233

Test Error Responses with WP-CLI


Sources: docs/getting-started/basic-examples.md113-116

Verify Error Handler Implementation


Sources: docs/troubleshooting/common-issues.md308-324

Best Practices

1. Use WP_Error for Business Logic Errors

Return WP_Error objects for validation failures, business rule violations, and expected error conditions:


2. Throw Exceptions for Unexpected Failures

Use exceptions for system failures, network errors, and unexpected conditions:


3. Provide Descriptive Error Messages

Error messages should be clear, specific, and actionable:


4. Use Semantic Error Codes

Choose error codes that describe the problem category:


5. Implement Custom Error Handlers for Production

Use custom error handlers to integrate with monitoring services:


6. Add Context to Error Logs

Include relevant context in error handler calls:


7. Test Error Paths

Write tests for both success and failure scenarios:


Sources: tests/Unit/Handlers/ToolsHandlerTest.php112-158

Refresh this wiki

On this page