VOOZH about

URL: https://deepwiki.com/WordPress/mcp-adapter/6-infrastructure

⇱ Infrastructure | WordPress/mcp-adapter | DeepWiki


Loading...
Menu

Infrastructure

The Infrastructure layer provides cross-cutting concerns that operate across the entire MCP Adapter system. This includes standardized error handling, observability tracking, and the conversion of WordPress abilities into MCP components.

Infrastructure Components:

  • Error Handling: McpErrorFactory and McpErrorHandlerInterface for standardized JSON-RPC error responses and logging
  • Observability: Metadata-driven event tracking via RequestRouter and McpObservabilityHandlerInterface
  • Domain Conversions: RegisterAbilityAsMcpTool, RegisterAbilityAsMcpResource, RegisterAbilityAsMcpPrompt classes transform WordPress abilities into MCP components

Sources: README.md110-126 README.md162-176

<old_str>

Error Handling

The error handling system provides standardized JSON-RPC error responses, HTTP status code mapping, and flexible logging through error handler implementations.

Error Handling Architecture

Error Handling Flow from Request to Response


Sources: includes/Infrastructure/ErrorHandling/McpErrorFactory.php includes/Transport/Infrastructure/HttpRequestHandler.php83-102

McpErrorFactory Class

The McpErrorFactory class centralizes error response creation, ensuring consistent JSON-RPC 2.0 error formatting across all components.

JSON-RPC Error Codes and HTTP Status Mapping

Error CodeConstantHTTP StatusDescription
-32700PARSE_ERROR400Invalid JSON in request body
-32600INVALID_REQUEST400Invalid JSON-RPC request format
-32601METHOD_NOT_FOUND404Requested method does not exist
-32602INVALID_PARAMS400Invalid method parameters
-32603INTERNAL_ERROR500Internal server error
-32001UNAUTHORIZED401Authentication required
-32002FORBIDDEN403Insufficient permissions

Sources: includes/Infrastructure/ErrorHandling/McpErrorFactory.php tests/Integration/HttpTransportTest.php228-248

JSON-RPC Error Response Format

Error responses follow JSON-RPC 2.0 specification:


Error Response Fields:

  • jsonrpc: Always "2.0"
  • id: Request ID from original request
  • error.code: JSON-RPC error code
  • error.message: Human-readable error description
  • error.data: Additional error context (optional)

Sources: includes/Transport/Infrastructure/HttpRequestHandler.php144-146 tests/Integration/HttpTransportTest.php303-317

Error Handler Interface

Custom error handlers implement McpErrorHandlerInterface:

MethodPurposeParameters
log()Record error eventsstring $message, array $context, string $type

Built-in Implementations:

ClassPurposeUse Case
ErrorLogMcpErrorHandlerWordPress error_log loggingDefault production logging
NullMcpErrorHandlerNo-op implementationTesting or external logging systems

Sources: includes/Infrastructure/ErrorHandling/Contracts/McpErrorHandlerInterface.php includes/Infrastructure/ErrorHandling/ErrorLogMcpErrorHandler.php includes/Infrastructure/ErrorHandling/NullMcpErrorHandler.php

WP_Error Integration

The system integrates with WordPress WP_Error objects for ability-level errors:

Error Handling Flow:

  1. Ability permission callbacks return WP_Error or false
  2. Handlers detect WP_Error or boolean false
  3. Convert to appropriate JSON-RPC error code
  4. Preserve error details in error.data field
  5. Log via error handler

Example WP_Error Conversion:

  • Permission callback returns WP_Error: Converts to -32002 (FORBIDDEN)
  • Execute callback returns WP_Error: Converts to -32603 (INTERNAL_ERROR)
  • Error message and data preserved in JSON-RPC response

Sources: includes/Handlers/Tools/ToolsHandler.php includes/Handlers/Resources/ResourcesHandler.php

Error Handler Configuration

Error handlers are configured at server creation time and injected into all components:


Sources: README.md453-471

Observability System

The observability system provides metadata-driven event tracking where request handlers attach metadata to responses, and RequestRouter extracts, records, and strips metadata before sending responses to clients.

Metadata-Driven Observability Architecture

Observability Flow Through RequestRouter


Sources: includes/Transport/Infrastructure/RequestRouter.php51-130

RequestRouter Observability Integration

The RequestRouter::route_request() method centralizes all observability logic:

RequestRouter Observability Processing Steps

StepActionCode Location
1Start timerincludes/Transport/Infrastructure/RequestRouter.php53
2Collect common tagsincludes/Transport/Infrastructure/RequestRouter.php56-63
3Route to handlerincludes/Transport/Infrastructure/RequestRouter.php65-81
4Extract _metadataincludes/Transport/Infrastructure/RequestRouter.php87
5Calculate duration (ms)includes/Transport/Infrastructure/RequestRouter.php84
6Merge tagsincludes/Transport/Infrastructure/RequestRouter.php96
7Record eventincludes/Transport/Infrastructure/RequestRouter.php102-109
8Strip _metadataincludes/Transport/Infrastructure/RequestRouter.php88

Sources: includes/Transport/Infrastructure/RequestRouter.php51-130

Event Structure

All observability events use unified structure:

FieldTypeDescription
eventstringEvent name (always 'mcp.request')
tagsarrayEvent metadata and context
duration_msfloatRequest duration in milliseconds

Common Event Tags:

  • method: MCP method name ('tools/call', 'resources/read', etc.)
  • transport: Transport type ('HTTP', 'STDIO')
  • server_id: MCP server identifier
  • request_id: JSON-RPC request ID
  • session_id: Session identifier (HTTP transport)
  • status: Request outcome ('success' or 'error')

Handler-Attached Metadata Tags:

  • ability_id: WordPress ability identifier
  • user_id: Current user ID
  • component_type: MCP component type ('tool', 'resource', 'prompt')

Error-Specific Tags:

  • error_code: JSON-RPC error code (-32601, etc.)
  • error_type: Exception class name
  • error_category: Error category ('arguments', 'validation', 'execution')

Sources: includes/Transport/Infrastructure/RequestRouter.php56-109

Exception Categorization

The RequestRouter::categorize_exception() method automatically categorizes exceptions:

Exception Category Mapping

Exception TypeCategoryTypical Cause
ArgumentCountErrorargumentsFunction argument count mismatch
ErrorsystemSystem-level errors
InvalidArgumentExceptionvalidationInput validation failures
LogicExceptionlogicProgramming logic errors
RuntimeExceptionexecutionRuntime execution failures
TypeErrortypeType-related errors
Other exceptionsunknownUncategorized exceptions

Sources: includes/Transport/Infrastructure/RequestRouter.php193-204

Parameter Sanitization

The RequestRouter::sanitize_params() method prevents sensitive data exposure in logs:

Sanitization Strategy:

  • Extract safe fields only: name, protocolVersion, uri, clientInfo.name
  • Record argument count and keys (not values)
  • Limit string lengths to prevent log bloat
  • Remove passwords, tokens, credentials

Sources: includes/Transport/Infrastructure/RequestRouter.php213-244

Observability Handler Interface

Custom observability handlers implement McpObservabilityHandlerInterface:

MethodPurposeParameters
record_event()Record observability eventstring $event, array $tags, float $duration_ms

Built-in Implementations:

ClassPurposeUse Case
ErrorLogMcpObservabilityHandlerLog events to error_logDebug and development
NullMcpObservabilityHandlerNo-op handlerProduction zero-overhead

Sources: includes/Infrastructure/Observability/Contracts/McpObservabilityHandlerInterface.php includes/Infrastructure/Observability/ErrorLogMcpObservabilityHandler.php includes/Infrastructure/Observability/NullMcpObservabilityHandler.php

McpObservabilityHelperTrait

The McpObservabilityHelperTrait provides reusable observability utilities:

Helper Trait Methods

MethodPurposeReturn Type
get_default_tags()Standard tags (site_id, user_id, timestamp)array
sanitize_tags()Remove sensitive data, limit lengtharray
format_metric_name()Add 'mcp.' prefix to event namesstring
merge_tags()Combine default and custom tagsarray
record_error_event()Standardized error event recordingvoid
categorize_error()Map exceptions to error categoriesstring

Sources: includes/Infrastructure/Observability/McpObservabilityHelperTrait.php38-137 </old_str> <new_str>

Domain Conversions

The domain conversion layer transforms WordPress abilities into MCP components (tools, resources, prompts). This conversion handles schema transformation, annotation mapping, and component-specific requirements.

Domain Conversion Architecture


Sources: README.md78-98 Diagram 3 from high-level architecture

Converter Classes

ClassPurposeKey Responsibilities
RegisterAbilityAsMcpToolConvert abilities to toolsSchema transformation, annotation mapping, tool-specific validation
RegisterAbilityAsMcpResourceConvert abilities to resourcesURI requirements, read-only semantics, content extraction
RegisterAbilityAsMcpPromptConvert abilities to promptsPrompt arguments, message structure, audience annotations

Sources: README.md82-96

Schema Transformation

The SchemaTransformer handles conversion between WordPress ability schemas and MCP-compatible schemas:

Transformation Operations:

  • Converts flattened schemas to object schemas
  • Validates input/output schema requirements
  • Ensures MCP specification compliance
  • Handles nested property structures

See Schema Transformation (4.2) for detailed schema conversion rules.

Sources: README.md82-84 Diagram 3

Annotation Mapping

The McpAnnotationMapper extracts MCP-specific annotations from ability metadata:

MCP Annotations:

  • meta.mcp.type: Component type (tool/resource/prompt)
  • meta.mcp.public: Visibility flag
  • meta.mcp.annotations: Tool annotations (readOnlyHint, destructiveHint, idempotentHint)
  • meta.mcp.audience: Prompt audience tags

Sources: README.md82-96

Error Handling System

The error handling system provides standardized JSON-RPC error responses and flexible logging through error handler implementations.

Error Response System


Sources: includes/Transport/Infrastructure/RequestRouter.php128 includes/Transport/Infrastructure/HttpRequestHandler.php83-102 tests/Integration/HttpTransportTest.php228-248

JSON-RPC Error Codes

The McpErrorFactory class provides standardized error codes per JSON-RPC 2.0 specification:

Error CodeConstantDescriptionHTTP Status
-32700PARSE_ERRORInvalid JSON in request body400
-32600INVALID_REQUESTInvalid JSON-RPC request format400
-32601METHOD_NOT_FOUNDRequested method does not exist404
-32602INVALID_PARAMSInvalid method parameters400
-32603INTERNAL_ERRORInternal server error500
-32001UNAUTHORIZEDAuthentication required401
-32002FORBIDDENInsufficient permissions403

Sources: tests/Integration/HttpTransportTest.php228-248 tests/Unit/Transport/Infrastructure/RequestRouterTest.php189

Error Response Format

All errors follow JSON-RPC 2.0 error response structure:


Sources: includes/Transport/Infrastructure/HttpRequestHandler.php144-146 tests/Integration/HttpTransportTest.php303-317

WP_Error Integration

The system integrates with WordPress WP_Error objects for ability-level errors:

Error Handling Flow:

  1. Ability permission callbacks return WP_Error or false
  2. Handlers convert WP_Error to JSON-RPC error format
  3. Error details preserved in error.data field
  4. Error logged via error handler

Sources: README.md22-26

Error Handler Interface

Custom error handlers implement McpErrorHandlerInterface:

MethodPurposeParameters
log()Record error eventsstring $message, array $context, string $type

Built-in Implementations:

  • ErrorLogMcpErrorHandler: Logs to WordPress error_log
  • NullMcpErrorHandler: No-op handler for testing

Sources: README.md113-116

Error Handling System

The MCP Adapter provides a flexible error handling system that allows both built-in WordPress-compatible logging and custom error handler implementations for integration with external monitoring systems.

Error Handler Architecture


Sources: README.md162-169

Error Handler Interface

The McpErrorHandlerInterface defines the contract for all error handling implementations:

MethodPurposeParameters
log()Record error eventsstring $message, array $context, string $type

Sources: README.md166

Built-in Error Handlers

ClassPurposeUse Case
ErrorLogMcpErrorHandlerWordPress-compatible loggingDefault production logging to WordPress error logs
NullMcpErrorHandlerNo-op implementationTesting environments or when external systems handle logging

Sources: README.md167-168

Observability System

The observability infrastructure provides zero-overhead metrics tracking with configurable handlers for integration with monitoring systems.

Observability Architecture


Sources: README.md170-176 src/Infrastructure/Observability/McpObservabilityHelperTrait.php1-139

Observability Helper Utilities

The McpObservabilityHelperTrait provides shared functionality for observability implementations:

MethodPurposeReturn Type
get_default_tags()Standard metric tags (site_id, user_id, timestamp)array
sanitize_tags()Remove sensitive data, limit lengtharray
format_metric_name()Consistent naming with 'mcp.' prefixstring
merge_tags()Combine default and custom tagsarray
record_error_event()Standardized error event recordingvoid
categorize_error()Map exceptions to error categoriesstring

Sources: src/Infrastructure/Observability/McpObservabilityHelperTrait.php38-137

Error Categorization

The system automatically categorizes exceptions for better observability:

Exception TypeCategoryDescription
ArgumentCountErrorargumentsFunction argument mismatches
ErrorsystemSystem-level errors
InvalidArgumentExceptionvalidationInput validation failures
LogicExceptionlogicProgramming logic errors
RuntimeExceptionexecutionRuntime execution failures
TypeErrortypeType-related errors

Sources: src/Infrastructure/Observability/McpObservabilityHelperTrait.php24-31

Infrastructure Integration Flow


Sources: README.md162-176 src/Infrastructure/Observability/McpObservabilityHelperTrait.php115-126

Server Configuration Integration

Infrastructure components are configured at the server level during creation:

ParameterTypePurpose
error_handler_classstringError handler implementation class name
observability_handler_classstringObservability handler implementation class name

The McpServer class instantiates these handlers and provides them to transport contexts and request handlers through dependency injection.

Sources: README.md388-404

Custom Implementation Patterns

Custom Error Handler Example


Custom Observability Handler Example


Sources: README.md466-495

Refresh this wiki

On this page