VOOZH about

URL: https://deepwiki.com/WordPress/mcp-adapter/5.2-request-router

⇱ Request Router | WordPress/mcp-adapter | DeepWiki


Loading...
Menu

Request Router

The RequestRouter is responsible for dispatching incoming MCP JSON-RPC method calls to the appropriate handler classes and integrating observability tracking for all requests. It acts as the central routing layer between transport implementations and domain-specific handlers.

For information about the HTTP transport layer that uses the router, see HTTP Transport. For details about session validation, see Session Management.


Purpose and Scope

The RequestRouter provides:

  1. Method-to-handler routing - Maps MCP method names (e.g., tools/call, resources/list) to handler instances
  2. Observability integration - Records timing, metadata, and status for every request
  3. Error standardization - Catches exceptions and converts them to JSON-RPC error responses
  4. Session coordination - Manages session creation during initialize requests
  5. Metadata extraction - Extracts handler-attached metadata for observability without exposing it to clients

The router is transport-agnostic and is injected into both HTTP and STDIO transports via the McpTransportContext.

Sources: includes/Transport/Infrastructure/RequestRouter.php1-246


Architecture Overview


Diagram: RequestRouter Architecture

The router receives method calls from transports, routes them to handlers via a closure-based routing table, extracts metadata for observability, and returns clean responses.

Sources: includes/Transport/Infrastructure/RequestRouter.php40-130 tests/Unit/Transport/Infrastructure/RequestRouterTest.php74-109


Request Flow and Timing


Diagram: Request Lifecycle Through Router

Every request is timed from entry to exit. The router ensures observability events are recorded regardless of success or failure, providing complete visibility into request processing.

Sources: includes/Transport/Infrastructure/RequestRouter.php51-130 tests/Unit/Transport/Infrastructure/RequestRouterTest.php260-291


Method Routing Table

The router maintains a method-to-handler mapping using PHP closures, defined in includes/Transport/Infrastructure/RequestRouter.php65-78:

MethodHandlerNotes
initializehandle_initialize_with_session()Special handling for session creation
pingSystemHandler::ping()Health check
tools/listToolsHandler::list_tools()List available tools
tools/list/allToolsHandler::list_all_tools()List all tools including private
tools/callToolsHandler::call_tool()Execute a tool
resources/listResourcesHandler::list_resources()List resources with cursor compatibility
resources/readResourcesHandler::read_resource()Read resource content
prompts/listPromptsHandler::list_prompts()List available prompts
prompts/getPromptsHandler::get_prompt()Get prompt with arguments
logging/setLevelSystemHandler::set_logging_level()Dynamic log level adjustment
completion/completeSystemHandler::complete()Argument completion
roots/listSystemHandler::list_roots()List resource roots

Method Not Found: If a method is not in the routing table, the router returns a JSON-RPC error with code -32601 (Method not found).

Sources: includes/Transport/Infrastructure/RequestRouter.php65-82 tests/Unit/Transport/Infrastructure/RequestRouterTest.php184-204


Observability Integration

Event Recording

The router records a single unified event named mcp.request for every request, with a status tag distinguishing success from error:


Diagram: Observability Event Recording Flow

Sources: includes/Transport/Infrastructure/RequestRouter.php86-110 tests/Unit/Transport/Infrastructure/RequestRouterTest.php260-291

Metadata Extraction

Handlers can attach metadata to their responses using a special _metadata field. The router extracts this metadata, merges it with common tags, and removes it from the client response:


Common Tags (always included):

  • method - MCP method name (e.g., tools/call)
  • transport - Transport name (e.g., HTTP, STDIO)
  • server_id - MCP server ID
  • params - Sanitized request parameters
  • request_id - JSON-RPC request ID
  • session_id - HTTP session ID (if available)

Status-specific Tags:

  • Success: status='success'
  • Error: status='error', error_code=<JSON-RPC error code>
  • Exception: status='error', error_type=<exception class>, error_category=<category>

Sources: includes/Transport/Infrastructure/RequestRouter.php86-110 includes/Transport/Infrastructure/RequestRouter.php206-244


Error Handling

Exception Categorization

When handlers throw exceptions, the router categorizes them for better observability:


Diagram: Exception Handling and Categorization

The categorization helps identify systemic issues (e.g., many validation errors might indicate schema problems).

Sources: includes/Transport/Infrastructure/RequestRouter.php112-130 includes/Transport/Infrastructure/RequestRouter.php186-204

Error Response Format

All errors are returned in a consistent format:


The router never returns double-wrapped errors (i.e., no nested jsonrpc/id/error structures).

Sources: includes/Transport/Infrastructure/RequestRouter.php180-184 tests/Unit/Transport/Infrastructure/RequestRouterTest.php184-204


Session Management

Initialize Request Handling

The initialize method receives special handling because it needs to create HTTP sessions:


Diagram: Initialize Session Creation Flow

The router stores the new session ID in result['_session_id'], which is later removed by HttpRequestHandler and converted to an HTTP header.

Sources: includes/Transport/Infrastructure/RequestRouter.php146-172 tests/Unit/Transport/Infrastructure/RequestRouterTest.php111-135

Session ID Handling

Session IDs flow through the system as follows:

  1. Initialize request: Router creates session via HttpSessionValidator::create_session()
  2. Router stores: result['_session_id'] = <new_session_id>
  3. HttpRequestHandler extracts: Reads _session_id from result
  4. HttpRequestHandler converts: Adds Mcp-Session-Id HTTP response header
  5. Subsequent requests: Client includes Mcp-Session-Id header, validated before routing

Sources: includes/Transport/Infrastructure/RequestRouter.php91-93 includes/Transport/Infrastructure/HttpRequestHandler.php192-195


Response Formatting

Cursor Compatibility

The router adds backward-compatible nextCursor fields to resource list responses:


This is applied automatically to resources/list responses in the routing table:


The empty string '' indicates no pagination is available. This maintains compatibility with clients expecting cursor-based pagination.

Sources: includes/Transport/Infrastructure/RequestRouter.php132-144 includes/Transport/Infrastructure/RequestRouter.php71 tests/Unit/Transport/Infrastructure/RequestRouterTest.php232-258


Parameter Sanitization

The router sanitizes request parameters before logging to prevent sensitive data exposure:

Sanitized Fields (logged safely):

  • name - Tool/resource/prompt name
  • protocolVersion - MCP protocol version
  • uri - Resource URI
  • clientInfo.name - Client application name
  • arguments_count - Number of arguments (not values)
  • arguments_keys - Argument names (not values)

Excluded from Logs:

  • Actual argument values
  • Sensitive user data
  • Large payloads

This ensures observability events remain useful without exposing confidential information.

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


Integration Points

McpTransportContext

The router is injected into transport implementations via McpTransportContext:


The context automatically instantiates a RequestRouter and makes it available via the request_router property.

Sources: tests/Unit/Transport/Infrastructure/RequestRouterTest.php368-389

HttpRequestHandler Usage

The HttpRequestHandler uses the router to process JSON-RPC requests:


The handler then converts the router's result into a WP_REST_Response with appropriate HTTP status codes.

Sources: includes/Transport/Infrastructure/HttpRequestHandler.php183-195


Testing

The router is tested extensively in tests/Unit/Transport/Infrastructure/RequestRouterTest.php:

Key Test Coverage:

  • Method routing to all handlers
  • Observability event recording (timing, tags, status)
  • Error handling and categorization
  • Session creation during initialize
  • Cursor compatibility
  • Metadata extraction
  • Unknown method handling

Example Test:


Sources: tests/Unit/Transport/Infrastructure/RequestRouterTest.php260-291