transport_context = $transport_context; $this->decoder = new JsonRpcRequestDecoder(); } /** * Decode one raw JSON request or notification object. * * @since 0.7.0 * * @param string $raw_json Raw JSON payload. * * @return \stdClass Decoded object preserving JSON object/list identity. * * @throws \InvalidArgumentException If the JSON is malformed. * @throws \UnexpectedValueException If the root is not one object. * @throws \RangeException If an integer token exceeds the native range or a decoded number is non-finite. */ public function decode( string $raw_json ): \stdClass { return $this->decoder->decode( $raw_json ); } /** * Choose protocol processing, legacy session termination, or method rejection. * * @since 0.7.0 * * @param string $method HTTP method. * @param string|null $header_revision Protocol-version header, if supplied. * * @return string One of process, terminate-session, or reject. */ public function http_method_action( string $method, ?string $header_revision ): string { if ( 'POST' === $method ) { return 'process'; } $is_2025 = null === $header_revision || McpVersionNegotiator::is_negotiable( $header_revision ); return $is_2025 && 'DELETE' === $method ? 'terminate-session' : 'reject'; } /** * Check whether this request needs an established legacy HTTP session. * * @since 0.7.0 * * @param \stdClass $message Decoded message before request-record hydration. * @param string|null $header_revision Protocol-version header, if supplied. * * @return bool True for legacy requests other than initialize; false for selection failures. */ public function requires_2025_11_25_http_session( \stdClass $message, ?string $header_revision ): bool { $generic = $this->decoder->to_associative( $message ); if ( ! is_array( $generic ) || ! isset( $generic['method'] ) || ! is_string( $generic['method'] ) ) { return false; } $selection = $this->select_revision( $generic, array( 'protocol_version' => $header_revision ), null, false ); if ( ! is_string( $selection ) ) { return false; } return Schemas::V2025_11_25 === $selection && 'initialize' !== $generic['method']; } /** * Map a processed response through the selected revision's HTTP policy. * * @since 0.7.0 * * @param \WP\McpSchema\Record|array $response Processed response. * @param \WP\MCP\Core\McpRequestContext|null $context Selected context, or null for an early failure. * @param \stdClass $message Decoded message used to recover revision selection when needed. * @param string|null $header_revision Protocol-version header, if supplied. * * @return int HTTP status selected for the response error code and revision. */ public function http_response_status( $response, ?McpRequestContext $context, \stdClass $message, ?string $header_revision ): int { $code = $this->response_error_code( $response ); if ( 0 === $code ) { return 200; } $revision = null === $context ? null : $context->revision(); if ( null === $revision ) { $generic = $this->decoder->to_associative( $message ); $selection = is_array( $generic ) ? $this->select_revision( $generic, array( 'protocol_version' => $header_revision ), null, false ) : null; $revision = is_string( $selection ) ? $selection : null; } if ( null === $revision ) { return McpErrorFactory::mcp_error_to_http_status( $code ); } return Schemas::V2026_07_28 === $revision && McpErrorFactory::INVALID_PARAMS === $code ? 400 : McpErrorFactory::mcp_error_to_http_status( $code ); } /** * Process one decoded request or supported notification. * * @param \stdClass $message Decoded JSON object. * @param string $transport Transport name. * @param array $transport_metadata Transport metadata and headers. * @param array|null $client_params_2025_11_25 Initialize params for an established 2025 connection. * @return array{ * context: \WP\MCP\Core\McpRequestContext|null, * method: string|null, * id: mixed, * notification: bool, * response: \WP\McpSchema\Record|array|null, * initializeParams: array|null * } * @since 0.7.0 */ public function process( \stdClass $message, string $transport, array $transport_metadata = array(), ?array $client_params_2025_11_25 = null ): array { $generic = $this->decoder->to_associative( $message ); if ( ! is_array( $generic ) ) { return $this->failure( McpErrorFactory::invalid_request( null, 'Message must be an object' ) ); } $id = $generic['id'] ?? null; $safe_id = is_string( $id ) || is_int( $id ) ? $id : null; $method = isset( $generic['method'] ) && is_string( $generic['method'] ) ? $generic['method'] : null; $notification = '2.0' === ( $generic['jsonrpc'] ?? null ) && null !== $method && ! array_key_exists( 'id', $generic ); if ( '2.0' !== ( $generic['jsonrpc'] ?? null ) || null === $method ) { return $this->failure( McpErrorFactory::invalid_request( $safe_id, 'Invalid JSON-RPC request envelope' ), $method, $safe_id, $notification ); } if ( ! $notification && ! is_string( $id ) && ! is_int( $id ) ) { return $this->failure( McpErrorFactory::invalid_request( null, 'Request id must be a string or integer' ), $method, null, false ); } // Notification failures carry error data for transport status selection, not response-record hydration. $selection = $this->select_revision( $generic, $transport_metadata, $client_params_2025_11_25 ); if ( is_array( $selection ) ) { $schema = McpErrorFactory::UNSUPPORTED_VERSION === ( $selection['error']['code'] ?? null ) ? $this->transport_context->mcp_server->get_schemas()->forVersion( Schemas::V2026_07_28 ) : null; $response = $notification || null === $schema ? $selection : $this->hydrate_error( $selection, $schema ); return $this->failure( $response, $method, $id, $notification ); } $schema = $this->transport_context->mcp_server->get_schemas()->forVersion( $selection ); $header_error = Schemas::V2026_07_28 === $selection ? $this->validate_2026_07_28_envelope_headers( $generic, $transport, $transport_metadata ) : null; if ( null !== $header_error ) { return $this->failure( $notification ? $header_error : $this->hydrate_error( $header_error, $schema ), $method, $id, $notification ); } try { $request_context = Schemas::V2026_07_28 === $selection ? $this->context_2026_07_28( $message, $transport, $transport_metadata ) : $this->context_2025_11_25( $generic, $transport, $transport_metadata, $client_params_2025_11_25 ); } catch ( \Throwable $throwable ) { $error = McpErrorFactory::invalid_params( $id, $throwable->getMessage() ); return $this->failure( $notification ? $error : $this->hydrate_error( $error, $schema ), $method, $id, $notification ); } $header_error = Schemas::V2026_07_28 === $selection ? $this->validate_2026_07_28_parameter_headers( $generic, $request_context, $transport_metadata ) : null; if ( null !== $header_error ) { return $this->failure( $notification ? $header_error : $this->hydrate_error( $header_error, $schema ), $method, $id, $notification, $request_context ); } if ( $notification ) { if ( ! $this->allows_notification( $selection, $method, $schema ) ) { return array( 'context' => $request_context, 'method' => $method, 'id' => null, 'notification' => true, 'response' => null, 'initializeParams' => null, ); } try { $this->hydrate_inbound( $method, true, $schema, $message ); } catch ( \Throwable $throwable ) { return array( 'context' => $request_context, 'method' => $method, 'id' => null, 'notification' => true, 'response' => null, 'initializeParams' => null, ); } return array( 'context' => $request_context, 'method' => $method, 'id' => null, 'notification' => true, 'response' => null, 'initializeParams' => null, ); } if ( ! $this->allows_request( $selection, $method, $schema ) ) { $error = McpErrorFactory::method_not_found( $id, $method ); return $this->failure( $this->hydrate_error( $error, $schema ), $method, $id, false, $request_context ); } try { $request = $this->hydrate_inbound( $method, false, $schema, $message ); } catch ( \Throwable $throwable ) { $error = McpErrorFactory::invalid_params( $id, $throwable->getMessage() ); return $this->failure( $this->hydrate_error( $error, $schema ), $method, $id, false, $request_context ); } $params = $generic['params'] ?? array(); if ( is_array( $params ) && ( array_key_exists( 'requestState', $params ) || array_key_exists( 'inputResponses', $params ) ) && ( Schemas::V2026_07_28 !== $selection || 'tools/call' !== $method ) ) { $error = McpErrorFactory::invalid_params( $id, 'Continuation parameters are supported only for direct MCP 2026-07-28 tool calls.' ); return $this->failure( $this->hydrate_error( $error, $schema ), $method, $id, false, $request_context ); } $response = $this->transport_context->request_router->route_request_with_completion( $request, $request_context, $transport, function ( $result ) use ( $method, $id, $schema, $selection ): Record { if ( is_array( $result ) && isset( $result['error'] ) ) { return $this->hydrate_error( $result, $schema ); } $projected = Schemas::V2026_07_28 === $selection ? $this->project_2026_07_28_result( $method, $result, $schema ) : $this->project_2025_11_25_result( $method, $result, $schema ); return Schemas::V2026_07_28 === $selection ? $this->hydrate_2026_07_28_success( $method, $id, $projected, $schema ) : $this->hydrate_2025_11_25_success( $id, $projected, $schema ); } ); if ( ! $response instanceof Record ) { $response = $this->hydrate_error( $response, $schema ); } $initialize_params = Schemas::V2025_11_25 === $selection && $this->is_success_response( $response ) ? $this->initialize_params( $method, $request ) : null; return array( 'context' => $request_context, 'method' => $method, 'id' => $id, 'notification' => false, 'response' => $response, 'initializeParams' => $initialize_params, ); } /** * Whether one implemented request is available in the selected schema. * * @param string $revision Selected schema revision. * @param string $method Requested method name. * @param \WP\McpSchema\Schema $schema Catalog used to check protocol availability. * * @return bool Whether both the Adapter and catalog support the request. */ private function allows_request( string $revision, string $method, Schema $schema ): bool { $shared = array( 'tools/list', 'tools/call', 'resources/list', 'resources/templates/list', 'resources/read', 'prompts/list', 'prompts/get', ); if ( in_array( $method, $shared, true ) ) { return $schema->allowsClientRequest( $method ); } $implemented = Schemas::V2026_07_28 === $revision ? 'server/discover' === $method : in_array( $method, array( 'initialize', 'ping' ), true ); return $implemented && $schema->allowsClientRequest( $method ); } /** * Whether one implemented notification is available in the selected schema. * * @param string $revision Selected schema revision. * @param string $method Notification method. * @param \WP\McpSchema\Schema $schema Catalog used to check notification availability. * * @return bool Whether both the Adapter and catalog support the notification. */ private function allows_notification( string $revision, string $method, Schema $schema ): bool { return Schemas::V2025_11_25 === $revision && 'notifications/initialized' === $method && $schema->allowsClientNotification( $method ); } /** * Select one exact revision before context construction or hydration. * * @param array $generic Associative view of the decoded message. * @param array $metadata Transport metadata including the protocol-version header. * @param array|null $client_params_2025_11_25 Stored legacy initialization parameters. * @param bool $enforce_lifecycle Whether requests must already have legacy initialization context. * * @return string|array */ private function select_revision( array $generic, array $metadata, ?array $client_params_2025_11_25, bool $enforce_lifecycle = true ) { $method = $generic['method']; $params = is_array( $generic['params'] ?? null ) ? $generic['params'] : array(); $meta = is_array( $params['_meta'] ?? null ) ? $params['_meta'] : array(); $body_revision = isset( $meta['io.modelcontextprotocol/protocolVersion'] ) && is_string( $meta['io.modelcontextprotocol/protocolVersion'] ) ? $meta['io.modelcontextprotocol/protocolVersion'] : null; $header_revision = isset( $metadata['protocol_version'] ) && is_string( $metadata['protocol_version'] ) ? $metadata['protocol_version'] : null; if ( Schemas::V2026_07_28 === $body_revision || Schemas::V2026_07_28 === $header_revision ) { return Schemas::V2026_07_28; } $requested = is_string( $body_revision ) ? $body_revision : $header_revision; if ( null !== $requested && ! McpVersionNegotiator::is_negotiable( $requested ) ) { return McpErrorFactory::unsupported_protocol_version( $generic['id'] ?? null, $requested, McpVersionNegotiator::SUPPORTED_PROTOCOL_VERSIONS ); } if ( 'initialize' === $method ) { return Schemas::V2025_11_25; } if ( $enforce_lifecycle && null === $client_params_2025_11_25 ) { return McpErrorFactory::invalid_request( $generic['id'] ?? null, 'The 2025 lifecycle requires initialization before this request' ); } return Schemas::V2025_11_25; } /** * Construct the 2025 initialization/session context. * * The negotiated identifier comes from the client's own proposal, so a * legacy revision is echoed while the 2025-11-25 schema serves it. See * {@see McpVersionNegotiator::LEGACY_PROTOCOL_VERSIONS}. * * @param array $generic Associative request data. * @param string $transport Transport name. * @param array $metadata Transport-owned metadata. * @param array|null $client_params_2025_11_25 Stored legacy initialization parameters. * * @return \WP\MCP\Core\McpRequestContext Legacy context retaining the negotiated identifier. */ private function context_2025_11_25( array $generic, string $transport, array $metadata, ?array $client_params_2025_11_25 ): McpRequestContext { $params = 'initialize' === $generic['method'] ? ( $generic['params'] ?? array() ) : ( $client_params_2025_11_25 ?? array() ); $capabilities = $this->to_object( $params['capabilities'] ?? array() ); $client_info = isset( $params['clientInfo'] ) ? $this->to_object( $params['clientInfo'] ) : null; $negotiated = self::negotiated_protocol_version( $params ); $schema = $this->transport_context->mcp_server->get_schemas()->forVersion( McpVersionNegotiator::schema_version_for( $negotiated ) ); return new McpRequestContext( $schema, $capabilities, $client_info, $transport, $metadata, $negotiated ); } /** * Resolve the protocol version negotiated from stored or inbound 2025 initialize params. * * @param array $client_params Initialize params. * @since 0.7.0 */ public static function negotiated_protocol_version( array $client_params ): string { $proposed = $client_params['protocolVersion'] ?? null; return McpVersionNegotiator::negotiate( is_string( $proposed ) ? $proposed : '' ); } /** * Construct the 2026 per-request context. * * @param \stdClass $message Decoded request carrying modern metadata. * @param string $transport Transport name. * @param array $metadata Transport-owned metadata. * * @return \WP\MCP\Core\McpRequestContext Context built from modern request metadata. */ private function context_2026_07_28( \stdClass $message, string $transport, array $metadata ): McpRequestContext { $meta = $message->params->_meta ?? null; $revision = $meta->{'io.modelcontextprotocol/protocolVersion'} ?? null; $capabilities = $meta->{'io.modelcontextprotocol/clientCapabilities'} ?? null; if ( Schemas::V2026_07_28 !== $revision || ! $capabilities instanceof \stdClass ) { throw new \InvalidArgumentException( '2026 requests require exact protocolVersion and object clientCapabilities metadata.' ); } $client_info = isset( $meta->{'io.modelcontextprotocol/clientInfo'} ) && $meta->{'io.modelcontextprotocol/clientInfo'} instanceof \stdClass ? $meta->{'io.modelcontextprotocol/clientInfo'} : null; $schema = $this->transport_context->mcp_server->get_schemas()->forVersion( Schemas::V2026_07_28 ); return new McpRequestContext( $schema, $capabilities, $client_info, $transport, $metadata ); } /** * Apply exact 2025-11-25 result projection and hydrate the result root. * * @param string $method Method determining the result record type. * @param mixed $result Logical handler result. * @param \WP\McpSchema\Schema $schema Selected legacy catalog. * * @return \WP\McpSchema\Record Projected result record. */ private function project_2025_11_25_result( string $method, $result, Schema $schema ): Record { if ( is_array( $result ) && isset( $result['structuredContent'] ) && is_array( $result['structuredContent'] ) && self::is_list( $result['structuredContent'] ) ) { unset( $result['structuredContent'] ); } return $this->hydrate_result( $method, $result, $schema ); } /** * Apply exact 2026-07-28 result projection and hydrate the result root. * * @param string $method Method determining result type and cache defaults. * @param mixed $result Logical handler result. * @param \WP\McpSchema\Schema $schema Selected modern catalog. * * @return \WP\McpSchema\Record Result record including Adapter-supplied modern defaults. */ private function project_2026_07_28_result( string $method, $result, Schema $schema ): Record { if ( ! is_array( $result ) ) { return $this->hydrate_result( $method, $result, $schema ); } $input_required = 'input_required' === ( $result['resultType'] ?? null ); if ( $input_required && 'tools/call' !== $method ) { throw new \UnexpectedValueException( 'MRTR is implemented for direct tools/call handlers only.' ); } $result['resultType'] = $input_required ? 'input_required' : 'complete'; if ( in_array( $method, array( 'server/discover', 'tools/list', 'prompts/list', 'resources/list', 'resources/templates/list', 'resources/read' ), true ) ) { $result['ttlMs'] = 0; $result['cacheScope'] = 'private'; } // Validate provider metadata before adding serverInfo: adding a string key to a // list would turn it into an object, hiding the invalid shape from the schema. $meta_data = $result['_meta'] ?? array(); $meta = is_array( $meta_data ) ? $schema->fromArray( ResultMetaObject::class, $meta_data ) : $schema->fromValue( ResultMetaObject::class, $meta_data ); $meta = $meta->jsonSerialize(); $meta->{'io.modelcontextprotocol/serverInfo'} = array( 'name' => $this->transport_context->mcp_server->get_server_name(), 'version' => $this->transport_context->mcp_server->get_server_version(), ); $result['_meta'] = $meta; return $this->hydrate_result( $method, $result, $schema ); } /** * Hydrate logical handler output through one selected exact result root. * * @param string $method Method determining the result record type. * @param mixed $result Logical handler result. * @param \WP\McpSchema\Schema $schema Selected schema catalog. * * @return \WP\McpSchema\Record Method-specific result record. */ private function hydrate_result( string $method, $result, Schema $schema ): Record { if ( $result instanceof Record ) { if ( 'initialize' === $method && $result instanceof InitializeResult ) { return $result; } throw new \UnexpectedValueException( 'Handler returned an unexpected protocol record.' ); } if ( ! is_array( $result ) ) { throw new \UnexpectedValueException( 'Handler result must be logical array data.' ); } $data = $result; switch ( $method ) { case 'ping': return $schema->fromArray( EmptyResult::class, $data ); case 'server/discover': return $schema->fromArray( DiscoverResult::class, $data ); case 'tools/list': return $schema->fromArray( ListToolsResult::class, $data ); case 'tools/call': if ( Schemas::V2026_07_28 === $schema->version() && 'input_required' === ( $data['resultType'] ?? null ) ) { if ( ! array_key_exists( 'inputRequests', $data ) && ! array_key_exists( 'requestState', $data ) ) { throw new \UnexpectedValueException( 'Input-required results need inputRequests or requestState.' ); } return $schema->fromArray( InputRequiredResult::class, $data ); } return $schema->fromArray( CallToolResult::class, $data ); case 'resources/list': return $schema->fromArray( ListResourcesResult::class, $data ); case 'resources/templates/list': return $schema->fromArray( ListResourceTemplatesResult::class, $data ); case 'resources/read': return $schema->fromArray( ReadResourceResult::class, $data ); case 'prompts/list': return $schema->fromArray( ListPromptsResult::class, $data ); case 'prompts/get': return $schema->fromArray( GetPromptResult::class, $data ); default: // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Exception text is internal protocol diagnostics, not HTML output. throw new \LogicException( sprintf( 'No result projector for %s under %s.', $method, $schema->version() ) ); } } /** * Extract legacy initialization parameters for later requests. * * Client icons are omitted from the retained copy on every transport, so * later requests see a client_info() without `icons`. The schema allows * `clientInfo.icons` with `data:` URIs carrying kilobytes of image data, * the Adapter never renders a client's icon, and the HTTP copy is subject * to the per-session storage limit. The initialize request's own context * still carries the icons. This is an Adapter storage policy; MCP does not * require servers to retain them. * * @since 0.7.1 Omits `clientInfo.icons` from the stored parameters. * * @param string $method Dispatched method name. * @param \WP\McpSchema\Record $request Validated request record. * * @return array|null Plain initialization parameters, or null for another request type. */ private function initialize_params( string $method, Record $request ): ?array { if ( 'initialize' !== $method || ! $request instanceof InitializeRequest ) { return null; } $params = $this->decoder->to_associative( $request->getParams()->jsonSerialize() ); if ( ! is_array( $params ) ) { return null; } if ( isset( $params['clientInfo'] ) && is_array( $params['clientInfo'] ) ) { unset( $params['clientInfo']['icons'] ); } return $params; } /** * Hydrate one exact 2025-11-25 success envelope. * * @param string|int $id Request ID. * @param \WP\McpSchema\Record $result Validated result payload. * @param \WP\McpSchema\Schema $schema Selected legacy catalog. * * @return \WP\McpSchema\Record Legacy JSON-RPC result response. */ private function hydrate_2025_11_25_success( $id, Record $result, Schema $schema ): Record { return $schema->fromArray( JSONRPCResultResponse::class, array( 'jsonrpc' => '2.0', 'id' => $id, 'result' => $result, ) ); } /** * Hydrate one exact 2026-07-28 success envelope. * * @param string $method Method determining the response envelope type. * @param string|int|null $id Request ID. * @param \WP\McpSchema\Record $result Validated result payload. * @param \WP\McpSchema\Schema $schema Selected modern catalog. * * @return \WP\McpSchema\Record Method-specific modern result response. */ private function hydrate_2026_07_28_success( string $method, $id, Record $result, Schema $schema ): Record { $data = array( 'jsonrpc' => '2.0', 'id' => $id, 'result' => $result, ); switch ( $method ) { case 'server/discover': return $schema->fromArray( DiscoverResultResponse::class, $data ); case 'tools/list': return $schema->fromArray( ListToolsResultResponse::class, $data ); case 'tools/call': return $schema->fromArray( CallToolResultResponse::class, $data ); case 'resources/list': return $schema->fromArray( ListResourcesResultResponse::class, $data ); case 'resources/templates/list': return $schema->fromArray( ListResourceTemplatesResultResponse::class, $data ); case 'resources/read': return $schema->fromArray( ReadResourceResultResponse::class, $data ); case 'prompts/list': return $schema->fromArray( ListPromptsResultResponse::class, $data ); case 'prompts/get': return $schema->fromArray( GetPromptResultResponse::class, $data ); default: // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Exception text is internal protocol diagnostics, not HTML output. throw new \LogicException( sprintf( 'No response encoder for %s under %s.', $method, $schema->version() ) ); } } /** * Hydrate one implemented inbound root without dynamic class strings. * * @param string $method Request or notification method. * @param bool $notification Whether the message is a notification. * @param \WP\McpSchema\Schema $schema Selected catalog. * @param \stdClass $message Original decoded object to hydrate. * * @return \WP\McpSchema\Record Supported request or notification record. */ private function hydrate_inbound( string $method, bool $notification, Schema $schema, \stdClass $message ): Record { if ( in_array( $method, array( 'initialize', 'ping', 'notifications/initialized' ), true ) && Schemas::V2025_11_25 !== $schema->version() ) { // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Exception text is internal protocol diagnostics, not HTML output. throw new \LogicException( sprintf( '%s is not available under %s.', $method, $schema->version() ) ); } if ( 'server/discover' === $method && Schemas::V2026_07_28 !== $schema->version() ) { // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Exception text is internal protocol diagnostics, not HTML output. throw new \LogicException( sprintf( '%s is not available under %s.', $method, $schema->version() ) ); } if ( $notification && 'notifications/initialized' === $method ) { return $schema->fromValue( InitializedNotification::class, $message ); } switch ( $method ) { case 'initialize': return $schema->fromValue( InitializeRequest::class, $message ); case 'ping': return $schema->fromValue( PingRequest::class, $message ); case 'server/discover': return $schema->fromValue( DiscoverRequest::class, $message ); case 'tools/list': return $schema->fromValue( ListToolsRequest::class, $message ); case 'tools/call': return $schema->fromValue( CallToolRequest::class, $message ); case 'resources/list': return $schema->fromValue( ListResourcesRequest::class, $message ); case 'resources/templates/list': return $schema->fromValue( ListResourceTemplatesRequest::class, $message ); case 'resources/read': return $schema->fromValue( ReadResourceRequest::class, $message ); case 'prompts/list': return $schema->fromValue( ListPromptsRequest::class, $message ); case 'prompts/get': return $schema->fromValue( GetPromptRequest::class, $message ); default: // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Exception text is internal protocol diagnostics, not HTML output. throw new \LogicException( sprintf( 'No inbound root for %s under %s.', $method, $schema->version() ) ); } } /** * Hydrate a protocol error, falling back to a generic internal error. * * A failure to hydrate the fallback is allowed to propagate to the caller. * * @param array $error Logical JSON-RPC error envelope. * @param \WP\McpSchema\Schema $schema Selected schema catalog. * * @return \WP\McpSchema\Record Error response record. * * @throws \Throwable If the fallback error cannot be represented by the selected schema. */ private function hydrate_error( array $error, Schema $schema ): Record { $code = $error['error']['code'] ?? McpErrorFactory::INTERNAL_ERROR; try { if ( Schemas::V2026_07_28 === $schema->version() && McpErrorFactory::HEADER_MISMATCH === $code ) { return $schema->fromArray( HeaderMismatchError::class, $error ); } if ( Schemas::V2026_07_28 === $schema->version() && McpErrorFactory::UNSUPPORTED_VERSION === $code ) { return $schema->fromArray( UnsupportedProtocolVersionError::class, $error ); } return $schema->fromArray( JSONRPCErrorResponse::class, $error ); } catch ( \Throwable $throwable ) { $fallback = McpErrorFactory::internal_error( null, 'Unable to encode protocol error' ); return $schema->fromArray( JSONRPCErrorResponse::class, $fallback ); } } /** * Validate 2026-07-28 HTTP envelope headers before context hydration. * * @param array $message Associative decoded message. * @param string $transport Transport name; non-HTTP transports are ignored. * @param array $metadata Transport metadata containing normalized headers. * * @return array|null Header-mismatch error, or null when no mismatch applies. */ private function validate_2026_07_28_envelope_headers( array $message, string $transport, array $metadata ): ?array { if ( 'HTTP' !== strtoupper( $transport ) ) { return null; } $id = $message['id'] ?? null; $method = $message['method']; $headers = is_array( $metadata['headers'] ?? null ) ? array_change_key_case( $metadata['headers'], CASE_LOWER ) : array(); if ( Schemas::V2026_07_28 !== ( $headers['mcp-protocol-version'] ?? null ) ) { return McpErrorFactory::header_mismatch( $id, 'MCP-Protocol-Version is missing or does not match the request metadata' ); } $params = is_array( $message['params'] ?? null ) ? $message['params'] : array(); $meta = is_array( $params['_meta'] ?? null ) ? $params['_meta'] : array(); $body_revision = $meta['io.modelcontextprotocol/protocolVersion'] ?? null; if ( is_string( $body_revision ) && ( $headers['mcp-protocol-version'] ?? null ) !== $body_revision ) { return McpErrorFactory::header_mismatch( $id, 'MCP-Protocol-Version does not match the request body' ); } if ( $this->plain_header_value( $headers['mcp-method'] ?? null ) !== $method ) { return McpErrorFactory::header_mismatch( $id, 'Mcp-Method is missing or does not match the request body' ); } $name_field = 'resources/read' === $method ? 'uri' : 'name'; if ( in_array( $method, array( 'tools/call', 'resources/read', 'prompts/get' ), true ) ) { $header_name = $this->decode_header_value( $headers['mcp-name'] ?? null ); if ( null === $header_name || ( $params[ $name_field ] ?? null ) !== $header_name ) { return McpErrorFactory::header_mismatch( $id, 'Mcp-Name is missing or does not match the request body' ); } } return null; } /** * Validate 2026-07-28 x-mcp-header argument mirrors after context selection. * * @param array $message Associative decoded message. * @param \WP\MCP\Core\McpRequestContext $context Selected request context. * @param array $metadata Transport metadata containing normalized headers. * * @return array|null Parameter-header error, or null when no mismatch applies. */ private function validate_2026_07_28_parameter_headers( array $message, McpRequestContext $context, array $metadata ): ?array { if ( 'HTTP' !== strtoupper( $context->transport() ) || 'tools/call' !== ( $message['method'] ?? null ) ) { return null; } $params = is_array( $message['params'] ?? null ) ? $message['params'] : array(); $headers = is_array( $metadata['headers'] ?? null ) ? array_change_key_case( $metadata['headers'], CASE_LOWER ) : array(); return $this->validate_tool_parameter_headers( $params, $context, $headers, $message['id'] ?? null ); } /** * Validate x-mcp-header argument mirrors for a selected tool. * * @param array $params Tool-call parameters. * @param \WP\MCP\Core\McpRequestContext $context Context used to select the tool projection. * @param array $headers Case-normalized HTTP headers. * @param string|int|float|null $id Request ID. * * @return array|null Header-mismatch error, or null when validation succeeds or no tool applies. */ private function validate_tool_parameter_headers( array $params, McpRequestContext $context, array $headers, $id ): ?array { $name = $params['name'] ?? null; if ( ! is_string( $name ) ) { return null; } $tool = $this->transport_context->mcp_server->get_mcp_tool( $name ); if ( ! $tool || ! $tool->is_available_for( $context->schema() ) ) { return null; } $arguments = is_array( $params['arguments'] ?? null ) ? $params['arguments'] : array(); foreach ( $tool->get_header_annotations( $context->schema() ) as $annotation ) { $present = false; $value = $this->value_at_path( $arguments, $annotation['path'], $present ); $header_name = 'Mcp-Param-' . $annotation['name']; if ( ! $present || null === $value ) { continue; } // PHP and WordPress fold "-" and "_" in header names to one form, and // HttpRequestContext stores that form with hyphens. Fold the lookup key the // same way so annotation names containing "_" still find their header. $header_key = str_replace( '_', '-', strtolower( $header_name ) ); $raw_header = $headers[ $header_key ] ?? null; $header_value = $this->decode_header_value( $raw_header ); if ( null === $header_value || ! $this->header_value_matches( $header_value, $value, $annotation['type'] ) ) { return McpErrorFactory::header_mismatch( $id, sprintf( '%s is missing or does not match the request body', $header_name ) ); } } return null; } /** * Read one nested argument path. * * @param array $arguments Nested argument data. * @param list $path Property names to traverse. * @param bool $present Updated to indicate whether the complete path exists. * * @param-out bool $present Whether the path was present. * * @return mixed */ private function value_at_path( array $arguments, array $path, bool &$present ) { $value = $arguments; $present = true; foreach ( $path as $segment ) { if ( ! is_array( $value ) || ! array_key_exists( $segment, $value ) ) { $present = false; return null; } $value = $value[ $segment ]; } return $value; } /** * Decode a plain header value or an MCP Base64-sentinel value. * * @param mixed $value Supplied HTTP header value. * * @return string|null Decoded bytes, or null for invalid encoding or a non-string value. */ private function decode_header_value( $value ): ?string { if ( ! is_string( $value ) ) { return null; } if ( 0 !== strpos( $value, '=?base64?' ) || '?=' !== substr( $value, -2 ) ) { return $this->plain_header_value( $value ); } $decoded = base64_decode( substr( $value, 9, -2 ), true ); return false === $decoded ? null : $decoded; } /** * Accept a plain header value containing only printable ASCII. * * @param mixed $value Supplied HTTP header value. * * @return string|null Unchanged string, or null for invalid characters or a non-string value. */ private function plain_header_value( $value ): ?string { return is_string( $value ) && 1 === preg_match( '/^[\x20-\x7E]*$/D', $value ) ? $value : null; } /** * Compare a decoded primitive header value to the body value. * * @param string $header_value Decoded header value. * @param mixed $body_value Body value. * @param string $declared_type The x-mcp-header property type: string, integer, or boolean. */ private function header_value_matches( string $header_value, $body_value, string $declared_type ): bool { if ( is_bool( $body_value ) ) { return ( $body_value ? 'true' : 'false' ) === $header_value; } if ( is_int( $body_value ) || is_float( $body_value ) ) { if ( ! is_finite( $body_value ) || abs( $body_value ) > 9007199254740991 ) { return false; } // Integer declarations compare numerically, so a body 42.0 matches a header 42. // The strict decimal gate applies to the header only: "0x2A", " 42 ", and "1e1" // never coerce. Other declarations compare the body's decimal string. if ( 'integer' === $declared_type ) { return 1 === preg_match( '/^-?\d+(\.\d+)?$/D', $header_value ) && (float) $header_value === (float) $body_value; } return (string) $body_value === $header_value; } return is_string( $body_value ) && $body_value === $header_value; } /** * Copy object properties or associative input into a JSON object. * * @param mixed $value Object or array to copy; other values yield an empty object. * * @return \stdClass Object preserving nested JSON lists and objects. */ private function to_object( $value ): \stdClass { $object = new \stdClass(); $properties = $value instanceof \stdClass ? get_object_vars( $value ) : ( is_array( $value ) ? $value : array() ); foreach ( $properties as $key => $item ) { $object->{$key} = $this->copy_json_value( $item ); } return $object; } /** * Copy a decoded JSON value without collapsing lists into objects. * * @param mixed $value Value. * @return mixed */ private function copy_json_value( $value ) { if ( $value instanceof \stdClass ) { return $this->to_object( $value ); } if ( ! is_array( $value ) ) { return $value; } if ( array() === $value || array_keys( $value ) === range( 0, count( $value ) - 1 ) ) { return array_map( array( $this, 'copy_json_value' ), $value ); } return $this->to_object( $value ); } /** * Whether an encoded record is a successful JSON-RPC result response. * * @param \WP\McpSchema\Record $response Encoded response record. * * @return bool Whether the record has a result field and no error field. */ private function is_success_response( Record $response ): bool { return $response->has( 'result' ) && ! $response->has( 'error' ); } /** * Extract a native integer error code from a record or logical envelope. * * @param \WP\McpSchema\Record|array $response Processed response. * * @return int Error code, or zero when no safely representable code exists. */ private function response_error_code( $response ): int { $error = null; if ( is_array( $response ) ) { $error = $response['error'] ?? null; } elseif ( $response instanceof Record && $response->has( 'error' ) ) { $error = $response->get( 'error' ); } if ( $error instanceof Record && $error->has( 'code' ) ) { $code = $error->get( 'code' ); } elseif ( $error instanceof \stdClass ) { $code = $error->code ?? null; } elseif ( is_array( $error ) ) { $code = $error['code'] ?? null; } else { $code = null; } if ( is_int( $code ) ) { return $code; } if ( is_float( $code ) && is_finite( $code ) && floor( $code ) === $code && $code >= (float) PHP_INT_MIN && $code < -( (float) PHP_INT_MIN ) ) { return (int) $code; } return 0; } /** * PHP 7.4-compatible list detection. * * @param array $value Array to inspect. * * @return bool Whether the keys form a zero-based consecutive sequence. */ private static function is_list( array $value ): bool { return array() === $value || array_keys( $value ) === range( 0, count( $value ) - 1 ); } /** * Build a standard process failure result. * * @param \WP\McpSchema\Record|array $response Response. * @param string|null $method Identified method, if available. * @param string|int|float|null $id Request ID. * @param bool $notification Whether the failed message was a notification. * @param \WP\MCP\Core\McpRequestContext|null $context Selected context, if available. * * @return array{ * context: \WP\MCP\Core\McpRequestContext|null, * method: string|null, * id: mixed, * notification: bool, * response: \WP\McpSchema\Record|array|null, * initializeParams: array|null * } */ private function failure( $response, ?string $method = null, $id = null, bool $notification = false, ?McpRequestContext $context = null ): array { return array( 'context' => $context, 'method' => $method, 'id' => $id, 'notification' => $notification, 'response' => $response, 'initializeParams' => null, ); } }