VOOZH about

URL: https://deepwiki.com/WordPress/mcp-adapter/4.4-resources-handler

⇱ Resources Handler | WordPress/mcp-adapter | DeepWiki


Loading...
Menu

Example Usage

Complete example demonstrating resource registration and consumption through the ResourcesHandler.

Registering a Resource


Listing Resources


Reading a Resource


Error Example


Related Documentation

  • Page 4.1 (Creating Abilities) - Registering abilities with resource metadata
  • Page 4.3 (Tools Handler) - Tools handler for state modification operations
  • Page 4.5 (Prompts Handler) - Prompts handler for AI guidance templates
  • Page 3.3 (Security and Permissions) - Two-layer security model with permission callbacks
  • Page 5.2 (Request Router) - Request routing and observability integration
  • Page 6.1 (Error Handling) - Error factory and standardized error responses
  • Page 6.2 (Observability System) - Metadata-driven observability and event tracking

Resources Handler

The ResourcesHandler class processes MCP protocol requests for resource operations. Resources provide read-only access to data sources, uniquely identified by URIs. The handler implements two MCP protocol methods: resources/list and resources/read.

Resources are created by registering WordPress abilities with meta.mcp.type = 'resource' (see page 4.1). Unlike tools (page 4.3), resources are read-only and focused on data retrieval.

Handler Architecture

The ResourcesHandler class depends on McpServer for accessing registered resources and uses HandlerHelperTrait for parameter extraction. It delegates error logging to the server's error_handler.


ResourcesHandler Class Dependencies

DependencyTypePurpose
$mcpMcpServerAccess to resource registry and error handler
HandlerHelperTraitTraitParameter extraction via extract_params()
McpErrorFactoryStatic ClassStandardized error response generation

Sources: includes/Handlers/Resources/ResourcesHandler.php19-36

Method Overview

The handler implements two MCP protocol methods that map to the resources capability of the Model Context Protocol specification.

Handler MethodMCP Protocol MethodParametersReturns
list_resources()resources/listrequest_id (optional)Array of resources with metadata
read_resource()resources/readparams['uri'], request_id (optional)Resource contents with metadata

ResourcesHandler Method Flow

Sources: includes/Handlers/Resources/ResourcesHandler.php46-60 includes/Handlers/Resources/ResourcesHandler.php70-207

list_resources Method

Returns all registered resources from the MCP server. Each McpResource is serialized using its to_array() method, which formats the resource according to MCP protocol specifications.


list_resources() Execution Flow

Response Structure


The method iterates over all resources from McpServer::get_resources() and calls to_array() on each, collecting them into a resources array. The _metadata field tracks the component type and total count for observability purposes.

Sources: includes/Handlers/Resources/ResourcesHandler.php46-60

read_resource Method

Retrieves content for a specific resource identified by URI. This is the primary method for accessing resource data and includes comprehensive error handling and permission checking.

Execution Steps


read_resource() Decision Tree

The method performs the following operations in sequence:

StepOperationError Condition
1extract_params($params)Returns URI string
2Validate URI presenceMissing → missing_parameter error
3$mcp->get_resource($uri)Not found → resource_not_found error
4$resource->get_ability()WP_Error → ability_retrieval_failed error
5$ability->check_permissions()False/WP_Error → permission_denied error
6$ability->execute()WP_Error → wp_error error
7Catch exceptionsException → execution_failed error
8Return contentsSuccess with metadata

Sources: includes/Handlers/Resources/ResourcesHandler.php70-207

Parameter Extraction

The method uses HandlerHelperTrait::extract_params() to normalize parameter input. The URI parameter is required and must be a non-empty string.


If the URI is missing, the method returns immediately with a missing_parameter error.

Sources: includes/Handlers/Resources/ResourcesHandler.php72-82

Resource Lookup

The handler retrieves the McpResource instance by calling $mcp->get_resource($uri). This performs a registry lookup in the McpServer instance.


Resource Lookup in McpServer

If get_resource() returns null, the handler returns a resource_not_found error with the URI in the metadata.

Sources: includes/Handlers/Resources/ResourcesHandler.php85-97

URI-Based Resource Identification

Resources are uniquely identified by URIs stored in the meta.uri field during ability registration. The ResourcesHandler uses URIs as the primary lookup key for resources/read requests.

URI Format

URIs follow a scheme-based format to organize resources by domain. Common patterns include:

URI PatternExamplePurpose
wordpress://site/*wordpress://site/configSite-level data
wordpress://user/*wordpress://user/profileUser-specific data
wordpress://content/*wordpress://content/posts/recentContent data
wordpress://plugin/*wordpress://plugin/settingsPlugin-specific data

URI-Based Resource Lookup Flow

URI Registration

When an ability is registered with meta.mcp.type = 'resource', the meta.uri field becomes the resource's unique identifier. This URI must be globally unique within the MCP server instance.


The URI serves as both a human-readable identifier and a programmatic key for resource lookup.

Sources: includes/Handlers/Resources/ResourcesHandler.php85-86

Permission Flow

The read_resource() method implements a two-step permission check: first verifying resource existence, then delegating to the ability's permission_callback.


Permission Checking Flow in read_resource()

Permission Callback Delegation

The handler calls $ability->check_permissions() without arguments. The ability's permission_callback is responsible for implementing authorization logic.


Permission Callback Return Values

Return ValueMeaningHandler Behavior
truePermission grantedProceeds to execute()
falsePermission denied (generic)Returns permission_denied error
WP_ErrorPermission denied (detailed)Returns error with custom message and code

When check_permissions() returns a WP_Error, the error code becomes the failure_reason in metadata, and the error message is included in the response. This allows fine-grained permission denial explanations.

Sources: includes/Handlers/Resources/ResourcesHandler.php129-150

Permission Metadata

All permission-related errors include comprehensive metadata for debugging and observability:


Sources: includes/Handlers/Resources/ResourcesHandler.php141-149

Error Handling

The read_resource() method implements comprehensive error handling for all failure scenarios. Each error includes structured metadata for observability and debugging.

Error Response Structure

All errors follow a consistent format with both JSON-RPC error objects and metadata:


Error Scenarios

Error TypeTriggerError CodeFactory MethodMetadata Fields
Missing ParameterNo uri in params-32602missing_parameter()failure_reason: 'missing_parameter'
Resource Not Foundget_resource() returns null-32002resource_not_found()resource_uri, failure_reason: 'not_found'
Ability Retrieval Failedget_ability() returns WP_Error-32603internal_error()resource_uri, resource_name, failure_reason: 'ability_retrieval_failed', error_code
Permission Deniedcheck_permissions() returns false/WP_Error-32001permission_denied()resource_uri, resource_name, ability_name, failure_reason
WP_Error Returnedexecute() returns WP_Error-32603internal_error()resource_uri, resource_name, ability_name, failure_reason: 'wp_error', error_code
Exception ThrownException during execution-32603internal_error()resource_uri, failure_reason: 'execution_failed', error_type

Error Handling Decision Tree in read_resource()

Error Logging

The handler selectively logs errors using $mcp->error_handler->log(). Only internal failures (ability retrieval, WP_Error, exceptions) are logged; client errors (missing parameters, not found, permission denied) are not logged.

Logged Errors:

  1. Ability Retrieval Failed - When get_ability() returns WP_Error

    
    
  2. WP_Error During Execution - When execute() returns WP_Error

    
    
  3. Exception During Execution - When execute() throws exception

    
    

Sources: includes/Handlers/Resources/ResourcesHandler.php74-82 includes/Handlers/Resources/ResourcesHandler.php88-96 includes/Handlers/Resources/ResourcesHandler.php107-126 includes/Handlers/Resources/ResourcesHandler.php140-149 includes/Handlers/Resources/ResourcesHandler.php155-176 includes/Handlers/Resources/ResourcesHandler.php188-205

Content Types

Resources support two mutually exclusive content types returned by the ability's execute() callback: text or blob.

Text Content

Text resources return string content (JSON, XML, plain text, etc.). The ability's execute() callback should return the content directly or in a structured format.


Blob Content

Blob resources return base64-encoded binary data. The ability's execute() callback should return base64-encoded content with optional MIME type.


Content Extraction

The ResourcesHandler extracts content from the ability's execution result:

  1. If result is an array with contents key, uses contents value
  2. Otherwise, uses the entire result as contents
  3. Wraps in MCP protocol format: ['contents' => <value>]

Content Extraction Logic Sources: includes/Handlers/Resources/ResourcesHandler.php152-187

Data Serialization

Resources provide standardized serialization methods for MCP protocol compatibility. The to_array() method formats resource data according to specification requirements, while to_json() provides JSON encoding for transport.

MCP Protocol Format

The serialization follows MCP specification field naming conventions, with optional fields included only when they contain values.

Resource PropertyMCP FieldNotes
uriuriRequired, unique identifier
namenameOptional display name
descriptiondescriptionOptional description
mime_typemimeTypeOptional content type
texttextOptional text content
blobblobOptional binary content
annotationsannotationsOptional metadata

Resource Serialization Process Sources: src/Domain/Resources/McpResource.php308-339 src/Domain/Resources/McpResource.php346-348