get_status() ) { return $response; } $route = $request->get_route(); if ( ! is_string( $route ) || '' === $route ) { return $response; } // Only challenge on routes that actually belong to an MCP server. The // previous `strpos( $route, '/mcp' ) === 0` prefix test both over-matched // (any namespace merely STARTING with "mcp") and under-matched: a // database-registered server may use any `server_route_namespace`, and // those servers got no challenge header at all, so a client had nothing // to discover and the connector silently failed to authenticate. $resource_url = rest_url( ltrim( $route, '/' ) ); if ( AuthorizationController::server_id_from_resource( $resource_url ) <= 0 && 0 !== strpos( $route, '/mcp/' ) ) { return $response; } // RFC 9728 ยง3.1 โ€” the metadata URL inserts the well-known prefix between // the resource's host and its path. Emit that (not the legacy // `?resource=` form) so hosts which construct the URL themselves and // hosts which follow this header both land on the same document. $resource_path = (string) wp_parse_url( $resource_url, PHP_URL_PATH ); $metadata_url = home_url( '/.well-known/oauth-protected-resource/' . ltrim( $resource_path, '/' ) ); $header_value = sprintf( 'Bearer resource_metadata="%s"', esc_url_raw( $metadata_url ) ); if ( method_exists( $response, 'header' ) ) { $response->header( 'WWW-Authenticate', $header_value ); } return $response; } }